-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Contents.swift
92 lines (69 loc) · 2.55 KB
/
Contents.swift
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import PlaygroundSupport
import UIKit
final class LinearGradientLayer: CALayer {
enum Direction {
case vertical
case horizontal
case custom(start: CGPoint, end: CGPoint)
var points: (start: CGPoint, end: CGPoint) {
switch self {
case .vertical:
return (CGPoint(x: 0.5, y: 0.0), CGPoint(x: 0.5, y: 1.0))
case .horizontal:
return (CGPoint(x: 0.0, y: 0.5), CGPoint(x: 1.0, y: 0.5))
case let .custom(start, end):
return (start, end)
}
}
}
var direction: Direction = .vertical
var colorSpace: CGColorSpace = CGColorSpaceCreateDeviceRGB()
var colors: [CGColor]?
var locations: [CGFloat]?
var options: CGGradientDrawingOptions = CGGradientDrawingOptions(rawValue: 0)
// MARK: - Lifecycle
required override init() {
super.init()
masksToBounds = true
needsDisplayOnBoundsChange = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
required override init(layer: Any) {
super.init(layer: layer)
}
override func draw(in ctx: CGContext) {
ctx.saveGState()
guard let colors = colors, let gradient = CGGradient(colorsSpace: colorSpace,
colors: colors as CFArray, locations: locations) else { return }
let points = direction.points
ctx.drawLinearGradient(
gradient,
start: transform(points.start),
end: transform(points.end),
options: options
)
}
// MARK: - Private
private func transform(_ point: CGPoint) -> CGPoint {
return CGPoint(x: bounds.width * point.x, y: bounds.height * point.y)
}
}
final class GradientView: UIView {
lazy var gradientLayer = layer as? LinearGradientLayer
override class var layerClass: AnyClass {
return LinearGradientLayer.self
}
func updateGradient(with direction: LinearGradientLayer.Direction, colors: UIColor...) {
gradientLayer?.direction = direction
gradientLayer?.colors = colors.map { color in
color.cgColor
}
}
}
// MARK: - Example
let gradientView = GradientView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
let direction: LinearGradientLayer.Direction = .custom(start: CGPoint(x: 0, y: 0), end: CGPoint(x: 1, y: 1))
gradientView.updateGradient(with: direction, colors: .magenta, .purple, .cyan)
PlaygroundPage.current.liveView = gradientView