Skip to content

Instantly share code, notes, and snippets.

@mushu8
Created May 15, 2018 16:07
Show Gist options
  • Select an option

  • Save mushu8/7cd8cf7be948f09b0b25af1e3371333c to your computer and use it in GitHub Desktop.

Select an option

Save mushu8/7cd8cf7be948f09b0b25af1e3371333c to your computer and use it in GitHub Desktop.
animate an imageView from a cell to a navbar
func animateSelection(_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath) {
let burgerCell = collectionView.cellForItem(at: indexPath) as! BurgerCollectionViewCell
let burgerImageView = burgerCell.thumbnailImageView!
let snapshotImageViewFrame = self.view.convert(burgerImageView.frame,
from: burgerImageView.superview)
let snapshotImageView = burgerImageView.snapshotView(afterScreenUpdates: true)!
self.snapshotView = snapshotImageView
snapshotImageView.frame = snapshotImageViewFrame
self.view.addSubview(snapshotImageView)
let fadeOutAnimation = CABasicAnimation(keyPath: "opacity")
fadeOutAnimation.toValue = 0.3
fadeOutAnimation.fillMode = kCAFillModeForwards
fadeOutAnimation.isRemovedOnCompletion = false
let resizeAnimation = CABasicAnimation(keyPath: "bounds.size")
resizeAnimation.toValue = CGSize(width: 40, height: 40)
resizeAnimation.fillMode = kCAFillModeForwards
resizeAnimation.isRemovedOnCompletion = false
let pathAnimation = CAKeyframeAnimation(keyPath: "position")
pathAnimation.calculationMode = kCAAnimationPaced
pathAnimation.fillMode = kCAFillModeForwards;
pathAnimation.isRemovedOnCompletion = false
let navBarButtonItemView: UIView = self.navigationItem.rightBarButtonItem!.value(forKey: "view") as! UIView
let navItemFrame = self.view.convert(navBarButtonItemView.frame,
from: navBarButtonItemView.superview)
let endPoint = CGPoint(x: navItemFrame.midX, y: navItemFrame.midY)
let curvedPath = CGMutablePath()
curvedPath.move(to: CGPoint(x: snapshotImageViewFrame.midX, y: snapshotImageViewFrame.midY))
let controlPoint1 = CGPoint(x: navItemFrame.origin.x + 50, y: navItemFrame.origin.y + 50)
let controlPoint2 = CGPoint(x: navItemFrame.origin.x + 150, y: navItemFrame.origin.y + 150)
curvedPath.addCurve(to: endPoint, control1: controlPoint1, control2: controlPoint2)
pathAnimation.path = curvedPath
let groupAnimation = CAAnimationGroup()
groupAnimation.fillMode = kCAFillModeForwards
groupAnimation.isRemovedOnCompletion = false
groupAnimation.animations = [fadeOutAnimation, pathAnimation, resizeAnimation]
groupAnimation.duration = 0.7
groupAnimation.delegate = self
groupAnimation.setValue(snapshotImageView, forKey: "imageViewBeingAnimated")
snapshotImageView.layer.add(groupAnimation, forKey:"savingAnimation")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment