Skip to content

Instantly share code, notes, and snippets.

@dkun7944
Last active February 9, 2021 20:19
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkun7944/0482d04560e95fc81c3a6fe056aa31ea to your computer and use it in GitHub Desktop.
Save dkun7944/0482d04560e95fc81c3a6fe056aa31ea to your computer and use it in GitHub Desktop.
Extension to add a cool 3D floating effect to any UIView.
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