Skip to content

Instantly share code, notes, and snippets.

@jhays
Last active January 29, 2020 22:22
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 jhays/4fdb886620464ae03b38 to your computer and use it in GitHub Desktop.
Save jhays/4fdb886620464ae03b38 to your computer and use it in GitHub Desktop.
UIKit Motion / Shadow Effects Helper
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