func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewController(forKey: .from)!
let toViewController = transitionContext.viewController(forKey: .to)!
let sourceVC = fromViewController as! FlowerDetailController
let destinationVC = toViewController as! FlowerInfosController
transitionContext.containerView.insertSubview(toViewController.view, aboveSubview: fromViewController.view)
guard let selectedItem = destinationVC.selectedIndexPath, let infoCell = destinationVC.collectionView?.cellForItem(at: selectedItem) as? FlowerInfosCell else {
transitionContext.completeTransition(true)
return
}
let snapBackgroundView = UIView(frame: infoCell.contentView.frame)
snapBackgroundView.backgroundColor = infoCell.contentView.backgroundColor
snapBackgroundView.frame.origin = infoCell.contentView.convert(.zero, to: nil)
transitionContext.containerView.addSubview(snapBackgroundView)
let defaultScaleX: CGFloat = sourceVC.imageView.width / infoCell.imageView.width
let defaultScaleY: CGFloat = sourceVC.imageView.height / infoCell.imageView.height
snapBackgroundView.transform = CGAffineTransform(scaleX: defaultScaleX * 3, y: defaultScaleY * 3)
guard let snapImageView = sourceVC.imageView.snapshot else {
transitionContext.completeTransition(true)
return
}
snapImageView.frame.origin = sourceVC.imageView.convert(.zero, to: nil)
transitionContext.containerView.addSubview(snapImageView)
guard let snapDescription = sourceVC.descriptionView.snapshot else {
transitionContext.completeTransition(true)
return
}
snapDescription.frame.origin = sourceVC.descriptionView.convert(.zero, to: nil)
transitionContext.containerView.addSubview(snapDescription)
let animationScaleX: CGFloat = infoCell.imageView.frame.size.width / sourceVC.imageView.frame.size.width
let animationScaleY: CGFloat = infoCell.imageView.frame.size.height / sourceVC.imageView.frame.size.height
UIView.animate(withDuration: self.transitionDuration(using: transitionContext), animations: {
snapBackgroundView.transform = CGAffineTransform.identity
snapImageView.transform = CGAffineTransform(scaleX: animationScaleX, y: animationScaleY)
let cellImageOrigin: CGPoint = infoCell.imageView.convert(.zero, to: nil)
snapImageView.frame = CGRect(x: cellImageOrigin.x, y: cellImageOrigin.y, width: infoCell.imageView.frame.size.width, height: infoCell.imageView.frame.size.height)
snapDescription.frame.origin.y += sourceVC.view.height
}) { (finished) in
snapImageView.removeFromSuperview()
snapBackgroundView.removeFromSuperview()
snapDescription.removeFromSuperview()
transitionContext.completeTransition(true)
}
}