-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathShadows+UIKit.swift
More file actions
69 lines (63 loc) · 2.44 KB
/
Shadows+UIKit.swift
File metadata and controls
69 lines (63 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//
// Vitamin iOS
// Apache License 2.0
//
import UIKit
import VitaminCore
extension UIView {
/// Drops a shadow below this view.
/// - Parameters shadowType : the `VitaminShadow`you wqnt to drop
/// Since the shadow os added to the layer of the view, the background color is
/// forwarded from the view to the view'layer not to overlay the shadow
public func dropShadow(shadowType: VitaminShadow) {
layer.applyShadow(
color: shadowType.color,
opacity: shadowType.opacity,
shadowSize: shadowType.size,
blur: shadowType.blur,
spread: shadowType.spread)
if let backgroundCGColor = backgroundColor?.cgColor, shadowType != .none {
backgroundColor = nil
layer.backgroundColor = backgroundCGColor
}
}
/// Remove any shadow from this view by resetting all shadow properties on the view's layer
/// The layer background color is set back to the view if the layer color is not nil and the view's one is nil
public func removeShadow() {
dropShadow(shadowType: .none)
if let backgroundCGColor = backgroundColor?.cgColor, backgroundColor == nil {
layer.backgroundColor = nil
backgroundColor = UIColor(cgColor: backgroundCGColor)
}
}
}
extension CALayer {
/// Convenience mathod to apply a shadow on a CALayer
/// - Parameters:
/// - color: the `UIColor` of the shadow
/// - opacity: the opacity of the shadow
/// - shadowSize: a `CGSize`defining the position of the light source
/// - blur: blur of the shadow, as defined in Figma
/// - spread: spread of the shadow, as defined in Figma
func applyShadow(
color: UIColor = .black,
opacity: Float = 0.5,
shadowSize: CGSize = CGSize(width: 0, height: 2),
blur: CGFloat = 4,
spread: CGFloat = 0
) {
masksToBounds = false
shadowColor = color.cgColor
shadowOpacity = opacity
shadowOffset = shadowSize
// the shadow radius in iOS is equals to the blur divided by the screen scale
shadowRadius = blur / UIScreen.main.scale
if spread == 0 {
shadowPath = nil
} else {
let deltaX = -spread
let rect = bounds.insetBy(dx: deltaX, dy: deltaX)
shadowPath = UIBezierPath(rect: rect).cgPath
}
}
}