Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在过渡动画期间在两个ViewController之间共享图像_Ios_Objective C_Animation - Fatal编程技术网

Ios 在过渡动画期间在两个ViewController之间共享图像

Ios 在过渡动画期间在两个ViewController之间共享图像,ios,objective-c,animation,Ios,Objective C,Animation,自从IOS 7中提供UIViewControllerAnimatedTransitioning协议以来,我遇到了ViewController之间非常酷的转换。最近,我注意到Intacart的IOS应用程序中有一个特别有趣的应用程序 下面是我所说的慢动作动画: 首先,我认为这与作者在本教程中介绍的内容类似,有一些额外的淡入淡出动画: 但如果仔细观察,第一个viewController淡出时,两个viewController之间的产品图像似乎会发生变换。我认为有两个ViewController的原

自从IOS 7中提供UIViewControllerAnimatedTransitioning协议以来,我遇到了ViewController之间非常酷的转换。最近,我注意到Intacart的IOS应用程序中有一个特别有趣的应用程序

下面是我所说的慢动作动画:

首先,我认为这与作者在本教程中介绍的内容类似,有一些额外的淡入淡出动画:

但如果仔细观察,第一个viewController淡出时,两个viewController之间的产品图像似乎会发生变换。我认为有两个ViewController的原因是,当您向下滑动新视图时,您仍然可以看到其后面的原始视图,而不会更改布局

也许两个ViewController实际上具有产品图像(未淡出),并且以某种方式以完美的精度同时设置动画,其中一个淡入,另一个淡出

你认为那里到底发生了什么


如何编程这样一个过渡动画,使其看起来像两个ViewController之间共享的图像

可能是两个不同的视图和一个动画快照视图。事实上,这正是快照视图被发明的原因

我在我的应用程序中就是这样做的。当显示的视图上下滑动时,观察红色矩形的移动:

看起来红色视图正在离开第一个视图控制器并进入第二个视图控制器,但这只是一种错觉。如果有自定义过渡动画,则可以在过渡期间添加额外视图。因此,我创建了一个与第一个视图相似的快照视图,隐藏真实的第一个视图,然后移动快照视图,然后删除快照视图并显示真实的第二个视图

这里也是一样(这是一个很好的技巧,我在很多应用程序中都会用到):它看起来像是标题从第一个view controller表视图单元格中松开,滑到了第二个view controller中,但它只是一个快照视图:


以下是我们在动画转换(Swift 4)期间实现视图浮动的屏幕截图:

背后的想法:

  • 源视图和目标视图控制器符合
    可访问动画
    协议。我们使用此协议查找源视图和目标视图
  • 然后我们创建这些视图的快照并隐藏它们。相反,在同一位置显示快照
  • 然后我们制作快照动画
  • 在转换结束时,我们取消隐藏目标视图
  • 结果看起来源代码视图正在飞到目标

    文件:InterViewAnimation.swift

    // TODO: In case of multiple views, add another property which will return some unique string (identifier).
    protocol InterViewAnimatable {
       var targetView: UIView { get }
    }
    
    class InterViewAnimation: NSObject {
    
       var transitionDuration: TimeInterval = 0.25
       var isPresenting: Bool = false
    }
    
    extension InterViewAnimation: UIViewControllerAnimatedTransitioning {
    
       func transitionDuration(using: UIViewControllerContextTransitioning?) -> TimeInterval {
          return transitionDuration
       }
    
       func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
    
          let containerView = transitionContext.containerView
    
          guard
             let fromVC = transitionContext.viewController(forKey: .from),
             let toVC = transitionContext.viewController(forKey: .to) else {
                transitionContext.completeTransition(false)
                return
          }
    
          guard let fromTargetView = targetView(in: fromVC), let toTargetView = targetView(in: toVC) else {
             transitionContext.completeTransition(false)
             return
          }
    
          guard let fromImage = fromTargetView.caSnapshot(), let toImage = toTargetView.caSnapshot() else {
             transitionContext.completeTransition(false)
             return
          }
    
          let fromImageView = ImageView(image: fromImage)
          fromImageView.clipsToBounds = true
    
          let toImageView = ImageView(image: toImage)
          toImageView.clipsToBounds = true
    
          let startFrame = fromTargetView.frameIn(containerView)
          let endFrame = toTargetView.frameIn(containerView)
    
          fromImageView.frame = startFrame
          toImageView.frame = startFrame
    
          let cleanupClosure: () -> Void = {
             fromTargetView.isHidden = false
             toTargetView.isHidden = false
             fromImageView.removeFromSuperview()
             toImageView.removeFromSuperview()
          }
    
          let updateFrameClosure: () -> Void = {
             // https://stackoverflow.com/a/27997678/1418981
             // In order to have proper layout. Seems mostly needed when presenting.
             // For instance during presentation, destination view does'n account navigation bar height.
             toVC.view.setNeedsLayout()
             toVC.view.layoutIfNeeded()
    
             // Workaround wrong origin due ongoing layout process.
             let updatedEndFrame = toTargetView.frameIn(containerView)
             let correctedEndFrame = CGRect(origin: updatedEndFrame.origin, size: endFrame.size)
             fromImageView.frame = correctedEndFrame
             toImageView.frame = correctedEndFrame
          }
    
          let alimationBlock: (() -> Void)
          let completionBlock: ((Bool) -> Void)
    
          fromTargetView.isHidden = true
          toTargetView.isHidden = true
    
          if isPresenting {
             guard let toView = transitionContext.view(forKey: .to) else {
                transitionContext.completeTransition(false)
                assertionFailure()
                return
             }
             containerView.addSubviews(toView, toImageView, fromImageView)
             toView.frame = CGRect(origin: .zero, size: containerView.bounds.size)
             toView.alpha = 0
             alimationBlock = {
                toView.alpha = 1
                fromImageView.alpha = 0
                updateFrameClosure()
             }
             completionBlock = { _ in
                let success = !transitionContext.transitionWasCancelled
                if !success {
                   toView.removeFromSuperview()
                }
                cleanupClosure()
                transitionContext.completeTransition(success)
             }
          } else {
             guard let fromView = transitionContext.view(forKey: .from) else {
                transitionContext.completeTransition(false)
                assertionFailure()
                return
             }
             containerView.addSubviews(toImageView, fromImageView)
             alimationBlock = {
                fromView.alpha = 0
                fromImageView.alpha = 0
                updateFrameClosure()
             }
             completionBlock = { _ in
                let success = !transitionContext.transitionWasCancelled
                if success {
                   fromView.removeFromSuperview()
                }
                cleanupClosure()
                transitionContext.completeTransition(success)
             }
          }
    
          // TODO: Add more precise animation (i.e. Keyframe)
          if isPresenting {
             UIView.animate(withDuration: transitionDuration, delay: 0, options: .curveEaseIn,
                            animations: alimationBlock, completion: completionBlock)
          } else {
             UIView.animate(withDuration: transitionDuration, delay: 0, options: .curveEaseOut,
                            animations: alimationBlock, completion: completionBlock)
          }
       }
    }
    
    extension InterViewAnimation {
    
       private func targetView(in viewController: UIViewController) -> UIView? {
          if let view = (viewController as? InterViewAnimatable)?.targetView {
             return view
          }
          if let nc = viewController as? UINavigationController, let vc = nc.topViewController,
             let view = (vc as? InterViewAnimatable)?.targetView {
             return view
          }
          return nil
       }
    }
    
    用法:

    let sampleImage = UIImage(data: try! Data(contentsOf: URL(string: "https://placekitten.com/320/240")!))
    
    class InterViewAnimationMasterViewController: StackViewController {
    
       private lazy var topView = View().autolayoutView()
       private lazy var middleView = View().autolayoutView()
       private lazy var bottomView = View().autolayoutView()
    
       private lazy var imageView = ImageView(image: sampleImage).autolayoutView()
       private lazy var actionButton = Button().autolayoutView()
    
       override func setupHandlers() {
          actionButton.setTouchUpInsideHandler { [weak self] in
             let vc = InterViewAnimationDetailsViewController()
             let nc = UINavigationController(rootViewController: vc)
             nc.modalPresentationStyle = .custom
             nc.transitioningDelegate = self
             vc.handleClose = { [weak self] in
                self?.dismissAnimated()
             }
             // Workaround for not up to date laout during animated transition.
             nc.view.setNeedsLayout()
             nc.view.layoutIfNeeded()
             vc.view.setNeedsLayout()
             vc.view.layoutIfNeeded()
             self?.presentAnimated(nc)
          }
       }
    
       override func setupUI() {
          stackView.addArrangedSubviews(topView, middleView, bottomView)
          stackView.distribution = .fillEqually
    
          bottomView.addSubviews(imageView, actionButton)
    
          topView.backgroundColor = UIColor.red.withAlphaComponent(0.5)
          middleView.backgroundColor = UIColor.green.withAlphaComponent(0.5)
    
          bottomView.layoutMargins = UIEdgeInsets(horizontal: 15, vertical: 15)
          bottomView.backgroundColor = UIColor.yellow.withAlphaComponent(0.5)
    
          actionButton.title = "Tap to perform Transition!"
          actionButton.contentEdgeInsets = UIEdgeInsets(dimension: 8)
          actionButton.backgroundColor = .magenta
    
          imageView.layer.borderWidth = 2
          imageView.layer.borderColor = UIColor.magenta.withAlphaComponent(0.5).cgColor
       }
    
       override func setupLayout() {
          var constraints = LayoutConstraint.PinInSuperView.atCenter(imageView)
          constraints += [
             LayoutConstraint.centerX(viewA: bottomView, viewB: actionButton),
             LayoutConstraint.pinBottoms(viewA: bottomView, viewB: actionButton)
          ]
          let size = sampleImage?.size.scale(by: 0.5) ?? CGSize()
          constraints += LayoutConstraint.constrainSize(view: imageView, size: size)
          NSLayoutConstraint.activate(constraints)
       }
    }
    
    extension InterViewAnimationMasterViewController: InterViewAnimatable {
       var targetView: UIView {
          return imageView
       }
    }
    
    extension InterViewAnimationMasterViewController: UIViewControllerTransitioningDelegate {
    
       func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
          let animator = InterViewAnimation()
          animator.isPresenting = true
          return animator
       }
    
       func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
          let animator = InterViewAnimation()
          animator.isPresenting = false
          return animator
       }
    }
    
    class InterViewAnimationDetailsViewController: StackViewController {
    
       var handleClose: (() -> Void)?
    
       private lazy var imageView = ImageView(image: sampleImage).autolayoutView()
       private lazy var bottomView = View().autolayoutView()
    
       override func setupUI() {
          stackView.addArrangedSubviews(imageView, bottomView)
          stackView.distribution = .fillEqually
    
          imageView.contentMode = .scaleAspectFit
          imageView.layer.borderWidth = 2
          imageView.layer.borderColor = UIColor.purple.withAlphaComponent(0.5).cgColor
    
          bottomView.backgroundColor = UIColor.blue.withAlphaComponent(0.5)
    
          navigationItem.leftBarButtonItem = BarButtonItem(barButtonSystemItem: .done) { [weak self] in
             self?.handleClose?()
          }
       }
    }
    
    extension InterViewAnimationDetailsViewController: InterViewAnimatable {
       var targetView: UIView {
          return imageView
       }
    }
    
    可重用扩展:

    extension UIView {
    
       // https://medium.com/@joesusnick/a-uiview-extension-that-will-teach-you-an-important-lesson-about-frames-cefe1e4beb0b
       public func frameIn(_ view: UIView?) -> CGRect {
          if let superview = superview {
             return superview.convert(frame, to: view)
          }
          return frame
       }
    }
    
    
    extension UIView {
    
       /// The method drawViewHierarchyInRect:afterScreenUpdates: performs its operations on the GPU as much as possible
       /// In comparison, the method renderInContext: performs its operations inside of your app’s address space and does
       /// not use the GPU based process for performing the work.
       /// https://stackoverflow.com/a/25704861/1418981
       public func caSnapshot(scale: CGFloat = 0, isOpaque: Bool = false) -> UIImage? {
          var isSuccess = false
          UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, scale)
          if let context = UIGraphicsGetCurrentContext() {
             layer.render(in: context)
             isSuccess = true
          }
          let image = UIGraphicsGetImageFromCurrentImageContext()
          UIGraphicsEndImageContext()
          return isSuccess ? image : nil
       }
    }
    
    结果(gif动画):


    我认为这只是一个视图,因为如果向下滑动该视图,您可以将其忽略,因此可以在将子视图置于前面(隐藏)的同时变换图像视图,并将alpha=1设置为非常酷的,我想我几乎理解了正在发生的事情,但有几个问题;快照视图是指红色矩形吗?您是否将该新视图添加到transition containerView,它是您要转换到和从中转换的ViewController的父容器。你可以在里面放任何你想放的东西!它可以在演示继续时保持在那里。这也是如何实现的,例如,popover背后的屏幕变暗;这只是一个额外的视图。您是如何确定动画(使用自动布局)视图端点的位置的?有一些主要的问题…谢谢你的详细回答。现在尝试代码,我认为您缺少了更多扩展,或者出现了错误<代码>图像视图应为
    UIImageView
    UIView
    没有函数
    AddSubView