-
-
Notifications
You must be signed in to change notification settings - Fork 488
/
Copy pathGradientButton.swift
62 lines (52 loc) · 1.58 KB
/
GradientButton.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
//
// UIView+Gradient.swift
// Bark
//
// Created by huangfeng on 2023/2/10.
// Copyright © 2023 Fin. All rights reserved.
//
import UIKit
typealias GradientPoints = (startPoint: CGPoint, endPoint: CGPoint)
enum GradientOrientation {
case topRightBottomLeft
case topLeftBottomRight
case horizontal
case vertical
var startPoint: CGPoint {
return points.startPoint
}
var endPoint: CGPoint {
return points.endPoint
}
var points: GradientPoints {
switch self {
case .topRightBottomLeft:
return (CGPoint(x: 0.0, y: 1.0), CGPoint(x: 1.0, y: 0.0))
case .topLeftBottomRight:
return (CGPoint(x: 0.0, y: 0.0), CGPoint(x: 1, y: 1))
case .horizontal:
return (CGPoint(x: 0.0, y: 0.5), CGPoint(x: 1.0, y: 0.5))
case .vertical:
return (CGPoint(x: 0.0, y: 0.0), CGPoint(x: 0.0, y: 1.0))
}
}
}
class GradientButton: UIButton {
lazy var gradient: CAGradientLayer = {
let gradient = CAGradientLayer()
return gradient
}()
func applyGradient(withColours colours: [UIColor], gradientOrientation orientation: GradientOrientation) {
gradient.frame = self.bounds
gradient.colors = colours.map { $0.cgColor }
gradient.startPoint = orientation.startPoint
gradient.endPoint = orientation.endPoint
if gradient.superlayer == nil {
self.layer.insertSublayer(gradient, at: 0)
}
}
override func layoutSubviews() {
super.layoutSubviews()
gradient.frame = self.bounds
}
}