Created
June 24, 2020 20:12
-
-
Save perpeer/09e99e86a6b94efaf53f3bb9de1666aa to your computer and use it in GitHub Desktop.
Perspective Transform
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import UIKit | |
| class PerspectiveTransformView: UIView { | |
| override func awakeFromNib() { | |
| super.awakeFromNib() | |
| addPanGesture(self) | |
| } | |
| private func addPanGesture(_ view: UIView) { | |
| let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(sender:))) | |
| view.addGestureRecognizer(pan) | |
| } | |
| @objc private func handlePanGesture(sender: UIPanGestureRecognizer) { | |
| switch sender.state { | |
| case .began, .changed: | |
| perspectiveWithPan(sender: sender) | |
| case .ended, .cancelled, .failed: | |
| UIView.animate(withDuration: 0.5, delay: 0.1, options: [.allowUserInteraction, .allowAnimatedContent], animations: { | |
| self.transform = .identity | |
| }) | |
| default: break | |
| } | |
| } | |
| private func perspectiveWithPan(sender: UIPanGestureRecognizer) { | |
| let angle = sender.translation(in: self).x | |
| let velocity = sender.velocity(in: self).x | |
| print("angle: \(angle), velocity: \(velocity)") | |
| if -1500...1500 ~= velocity { | |
| var perspectiveTransform = CATransform3DIdentity | |
| perspectiveTransform.m34 = 1.0 / -700 | |
| perspectiveTransform = CATransform3DRotate(perspectiveTransform, velocity / 50 * .pi / 180.0, 0.0, 1.0, 0.0) | |
| self.layer.transform = perspectiveTransform | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment