Last active
January 29, 2020 22:22
-
-
Save jhays/4fdb886620464ae03b38 to your computer and use it in GitHub Desktop.
UIKit Motion / Shadow Effects Helper
This file contains 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 | |
import Foundation | |
extension UIView { | |
/// Adds a shadow to the layer of a view. | |
func addShadow(color: UIColor = .black, | |
opacity: Float = 0.4, | |
radius: Float = 3.0, | |
offset: CGSize = CGSize(width:0, height:2) | |
) { | |
self.layer.shadowColor = color.cgColor | |
self.layer.shadowOpacity = opacity | |
self.layer.shadowRadius = CGFloat(radius) | |
self.layer.shadowOffset = offset | |
} | |
/// Applies a UIInterpolationMotionEffect on the layer's shadowOffset | |
func addShadowParallaxMotionEffect(amount: Float) { | |
let motionX = UIInterpolatingMotionEffect(keyPath: "layer.shadowOffset.width", type: UIInterpolatingMotionEffect.EffectType.tiltAlongHorizontalAxis) | |
let motionY = UIInterpolatingMotionEffect(keyPath: "later.shadowOffset.height", type: UIInterpolatingMotionEffect.EffectType.tiltAlongVerticalAxis) | |
motionX.maximumRelativeValue = amount | |
motionX.minimumRelativeValue = -amount | |
motionY.maximumRelativeValue = amount | |
motionY.minimumRelativeValue = -amount | |
let group = UIMotionEffectGroup() | |
group.motionEffects = [motionX, motionY] | |
self.addMotionEffect(group) | |
} | |
/// Applies a UIInterpolationMotionEffect on the view's center. | |
func addParallaxMotionEffect(amount: Float) { | |
let motionX = UIInterpolatingMotionEffect(keyPath: "center.x", type: UIInterpolatingMotionEffect.EffectType.tiltAlongHorizontalAxis) | |
let motionY = UIInterpolatingMotionEffect(keyPath: "center.y", type: UIInterpolatingMotionEffect.EffectType.tiltAlongVerticalAxis) | |
motionX.maximumRelativeValue = CGFloat(amount) | |
motionX.minimumRelativeValue = CGFloat(-amount) | |
motionY.maximumRelativeValue = CGFloat(amount) | |
motionY.minimumRelativeValue = CGFloat(-amount) | |
let group = UIMotionEffectGroup() | |
group.motionEffects = [motionX, motionY] | |
self.addMotionEffect(group) | |
} | |
func addParallaxAndShadowEffects(amount: Float) { | |
self.addShadow() | |
self.addShadowParallaxMotionEffect(amount: amount) | |
self.addParallaxMotionEffect(amount: amount) | |
} | |
func addParallaxAndShadowEffects(motionParallaxAmount: Float, shadowParallaxAmount: Float) { | |
self.addShadow() | |
self.addParallaxMotionEffect(amount: motionParallaxAmount) | |
self.addShadowParallaxMotionEffect(amount: shadowParallaxAmount) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment