Tusker/Tusker/Screens/Gallery/Transitions/GalleryShrinkAnimationContr...

86 lines
3.2 KiB
Swift

// 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
}
let (sourceFrame, sourceCornerRadius) = fromVC.sourcesInfo[fromVC.currentIndex]
let originalVCFrame = fromVC.view.frame
let attachment = fromVC.attachments[fromVC.currentIndex]
guard let data = ImageCache.attachments.get(attachment.url),
let image = UIImage(data: data) else {
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
return
}
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" {
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 = sourceFrame
imageView.layer.cornerRadius = sourceCornerRadius
blackView.alpha = 0
}, completion: { _ in
blackView.removeFromSuperview()
imageView.removeFromSuperview()
if transitionContext.transitionWasCancelled {
toVC.view.removeFromSuperview()
}
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}