Last active
February 9, 2021 20:19
-
-
Save dkun7944/0482d04560e95fc81c3a6fe056aa31ea to your computer and use it in GitHub Desktop.
Extension to add a cool 3D floating effect to any UIView.
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
extension UIView { | |
func add3DFloatingEffect(withDepth depth: Double = 1 / 12, duration: Double = 5) { | |
let depthAngle = depth * .pi | |
let rotationAnimationY = CABasicAnimation(keyPath: "transform.rotation.y") | |
rotationAnimationY.fromValue = NSNumber(floatLiteral: -1 * depthAngle) | |
rotationAnimationY.toValue = NSNumber(floatLiteral: depthAngle) | |
rotationAnimationY.duration = duration | |
rotationAnimationY.repeatCount = Float(Int.max) | |
rotationAnimationY.autoreverses = true | |
rotationAnimationY.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) | |
layer.add(rotationAnimationY, forKey: "rotationAnimationZ") | |
let rotationAnimationX = CABasicAnimation(keyPath: "transform.rotation.x") | |
rotationAnimationX.fromValue = NSNumber(floatLiteral: -1 * depthAngle) | |
rotationAnimationX.toValue = NSNumber(floatLiteral: depthAngle) | |
rotationAnimationX.duration = duration | |
rotationAnimationX.repeatCount = Float(Int.max) | |
rotationAnimationX.autoreverses = true | |
rotationAnimationX.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) | |
rotationAnimationX.timeOffset = duration / 2 | |
layer.add(rotationAnimationX, forKey: "rotationAnimationX") | |
layer.transform.m34 = -1/500 | |
layer.anchorPoint = CGPoint(x: 0.5, y: 0.5) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment