// GalleryShrinkAnimationController.swift // Tusker // // Created by Shadowfacts on 6/14/19. // Copyright © 2019 Shadowfacts. All rights reserved. // import UIKit import Gifu class GalleryShrinkAnimationController: NSObject, UIViewControllerAnimatedTransitioning { let interactionController: LargeImageInteractionController? init(interactionController: LargeImageInteractionController?) { self.interactionController = interactionController } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.2 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let fromVC = transitionContext.viewController(forKey: .from) as? GalleryViewController, let toVC = transitionContext.viewController(forKey: .to) else { return } guard let sourceInfo = fromVC.sourcesInfo[fromVC.currentIndex], let image = fromVC.imageForDismissalAnimation() else { transitionContext.completeTransition(!transitionContext.transitionWasCancelled) return } let originalVCFrame = fromVC.view.frame let attachment = fromVC.attachments[fromVC.currentIndex] let ratio = image.size.width / image.size.height var width = originalVCFrame.width var height = width / ratio let maxHeight = fromVC.view.bounds.height - fromVC.view.safeAreaInsets.top - fromVC.view.safeAreaInsets.bottom if height > maxHeight { let scaleFactor = maxHeight / height width *= scaleFactor height = maxHeight } let originalFrame = CGRect(x: originalVCFrame.midX - width / 2, y: originalVCFrame.midY - height / 2, width: width, height: height) let imageView = GIFImageView(frame: originalFrame) imageView.image = image if attachment.url.pathExtension == "gif", let data = ImageCache.attachments.get(attachment.url) { imageView.animate(withGIFData: data) } imageView.contentMode = .scaleAspectFill imageView.layer.cornerRadius = 0 imageView.layer.masksToBounds = true let blackView = UIView(frame: originalVCFrame) blackView.backgroundColor = .black blackView.alpha = 1 let containerView = transitionContext.containerView containerView.addSubview(toVC.view) containerView.addSubview(blackView) containerView.addSubview(imageView) let duration = transitionDuration(using: transitionContext) UIView.animate(withDuration: duration, animations: { imageView.frame = sourceInfo.frame imageView.layer.cornerRadius = sourceInfo.cornerRadius blackView.alpha = 0 }, completion: { _ in blackView.removeFromSuperview() imageView.removeFromSuperview() if transitionContext.transitionWasCancelled { toVC.view.removeFromSuperview() } transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } }