-
Notifications
You must be signed in to change notification settings - Fork 0
/
JNGradientLabel.swift
435 lines (347 loc) · 20.2 KB
/
JNGradientLabel.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//
// JNGradientLabel.swift
// JNGradientLabel
//
// Copyright © 2021 SomeRandomiOSDev. All rights reserved.
//
import CoreGraphics
import UIKit
// swiftlint:disable discouraged_optional_collection
// MARK: - TextGradientLocation Definition
/// An enum that describes how a gradient should be drawn in relation to the text
@objc public enum TextGradientLocation: Int {
// MARK: Public Cases
/// The gradient should be drawn as the color of the text. The `textColor` property of the label and any text color specified as attributes on `attributedText` are ignored.
case foreground = 0
/// The gradient should be drawn as the background color of the text. The `backgroundColor` property of the label is ignored.
case background = 1
// MARK: Private Constants
fileprivate static let `default` = TextGradientLocation.foreground
}
// MARK: - RadialGradientRadiiScalingRule Definition
/// An enum that describes how the radial gradient radius should be scaled when drawing
@objc public enum RadialGradientRadiiScalingRule: Int {
// MARK: Public Cases
/// When scaling, the radial gradient radius should be multiplied by the current width of the label. `scaledRadius = radius * width`
case width = 0
/// When scaling, the radial gradient radius should be multiplied by the current height of the label. `scaledRadius = radius * height`
case height = 1
/// When scaling, the radial gradient radius should be multiplied by the smaller of the width and the height of the label. `scaledRadius = radius * min(width, height)`
case minimumBound = 2
/// When scaling, the radial gradient radius should be multiplied by the larger of the width and the height of the label. `scaledRadius = radius * max(width, height)`
case maximumBound = 3
// MARK: Public Constants
/// Same as `.maximumBound`
public static let `default` = RadialGradientRadiiScalingRule.maximumBound
}
// MARK: - JNGradientLabel Definition
open class JNGradientLabel: UILabel {
// MARK: Private Types
private enum GradientType: Codable {
// MARK: Public Cases
case axial(startPoint: CGPoint, endPoint: CGPoint)
case radial(startCenter: CGPoint, startRadius: CGFloat, endCenter: CGPoint, endRadius: CGFloat, radiiScalingRule: RadialGradientRadiiScalingRule)
// MARK: Private Types
// swiftlint:disable nesting
private enum CodingKeys: String, CodingKey {
// Axial/Radial
case type
case startPoint
case endPoint
// Radial
case startRadius
case endRadius
case radiiScalingRule
}
// swiftlint:enable nesting
// MARK: Encodable Protcol Requirements
func encode(to encoder: Encoder) throws {
switch self {
case let .axial(startPoint, endPoint):
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(0, forKey: .type)
try container.encode(startPoint, forKey: .startPoint)
try container.encode(endPoint, forKey: .endPoint)
case let .radial(startCenter, startRadius, endCenter, endRadius, radiiScalingRule):
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(1, forKey: .type)
try container.encode(startCenter, forKey: .startPoint)
try container.encode(startRadius, forKey: .startRadius)
try container.encode(endCenter, forKey: .endPoint)
try container.encode(endRadius, forKey: .endRadius)
try container.encode(radiiScalingRule.rawValue, forKey: .radiiScalingRule)
}
}
// MARK: Decodable Protocol Requirements
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
switch try values.decode(Int.self, forKey: .type) {
case 0: // Axial
self = .axial(startPoint: try values.decode(CGPoint.self, forKey: .startPoint),
endPoint: try values.decode(CGPoint.self, forKey: .endPoint))
case 1: // Radial
self = .radial(startCenter: try values.decode(CGPoint.self, forKey: .startPoint),
startRadius: try values.decode(CGFloat.self, forKey: .startRadius),
endCenter: try values.decode(CGPoint.self, forKey: .endPoint),
endRadius: try values.decode(CGFloat.self, forKey: .endRadius),
radiiScalingRule: RadialGradientRadiiScalingRule(rawValue: try values.decode(Int.self, forKey: .radiiScalingRule)) ?? .default)
default:
fatalError("Invalid gradient type")
}
}
}
private enum EncodingKeys: String {
// MARK: Cases
case gradientType
case gradientColors
case gradientLocations
case gradientOptions
case textGradientLocation
}
// MARK: Private Properties
private var gradientType: GradientType?
private var textImage: UIImage?
// MARK: Public Properties
/// The colors to be used when drawing the gradient
@objc open var gradientColors: [UIColor]? {
didSet {
if oldValue != gradientColors {
super.setNeedsDisplay()
}
}
}
/// The locations of the gradient colors specified in 'gradientColors'
@objc open var gradientLocations: [NSNumber]? {
didSet {
if oldValue != gradientLocations {
super.setNeedsDisplay()
}
}
}
/// The drawing options used when drawing the gradient
@objc open var gradientOptions: CGGradientDrawingOptions = [] {
didSet {
if oldValue != gradientOptions {
super.setNeedsDisplay()
}
}
}
/// The gradient location
@objc open var textGradientLocation: TextGradientLocation = .default {
didSet {
if oldValue != textGradientLocation {
super.setNeedsDisplay()
}
}
}
// MARK: Initialization
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
if let data = aDecoder.decodeObject(of: NSData.self, forKey: EncodingKeys.gradientType.rawValue) {
let type = try? JSONDecoder().decode(GradientType.self, from: data as Data)
gradientType = type
}
if let colors = aDecoder.decodeObject(of: NSArray.self, forKey: EncodingKeys.gradientColors.rawValue) {
gradientColors = (colors as Array).compactMap { $0 as? UIColor }
}
if let locations = aDecoder.decodeObject(of: NSArray.self, forKey: EncodingKeys.gradientLocations.rawValue) {
gradientLocations = (locations as Array).compactMap { $0 as? NSNumber }
}
gradientOptions = CGGradientDrawingOptions(rawValue: UInt32(bitPattern: aDecoder.decodeInt32(forKey: EncodingKeys.gradientOptions.rawValue)))
textGradientLocation = TextGradientLocation(rawValue: aDecoder.decodeInteger(forKey: EncodingKeys.textGradientLocation.rawValue)) ?? .default
}
// MARK: NSCoding Methods
override open func encode(with aCoder: NSCoder) {
super.encode(with: aCoder)
if let type = gradientType,
let data = try? JSONEncoder().encode(type) {
aCoder.encode(data, forKey: EncodingKeys.gradientType.rawValue)
}
if let colors = gradientColors {
aCoder.encode(colors as NSArray, forKey: EncodingKeys.gradientColors.rawValue)
}
if let locations = gradientLocations {
aCoder.encode(locations as NSArray, forKey: EncodingKeys.gradientLocations.rawValue)
}
aCoder.encode(Int32(bitPattern: gradientOptions.rawValue), forKey: EncodingKeys.gradientOptions.rawValue)
aCoder.encode(textGradientLocation.rawValue, forKey: EncodingKeys.textGradientLocation.rawValue)
}
// MARK: Public Methods
/// Sets the gradient type to `axial` (also known as linear) and sets the start and end points, and optionally the gradient colors and locations.
///
/// - parameter startPoint: The start point of the gradient with (0.0, 0.0) and (1.0, 1.0) representing the top-left and bottom-right corners of the label, respectively. Points whose coordinates lie outside of this range will be clamped
/// - parameter endPoint: The end point of the gradient with (0.0, 0.0) and (1.0, 1.0) representing the top-left and bottom-right corners of the label, respectively. Points whose coordinates lie outside of this range will be clamped
/// - parameter colors: The colors of the gradient
/// - parameter locations: The locations of the gradient colors
/// - parameter options: The gradient drawing options.
@objc open func setAxialGradientParameters(startPoint: CGPoint, endPoint: CGPoint, colors: [UIColor]? = nil, locations: [NSNumber]? = nil, options: CGGradientDrawingOptions = []) {
gradientOptions = options
gradientType = .axial(startPoint: startPoint.clamped(min: 0.0, max: 1.0),
endPoint: endPoint.clamped(min: 0.0, max: 1.0))
if let colors = colors { gradientColors = colors }
if let locations = locations { gradientLocations = locations }
super.setNeedsDisplay()
}
/// Sets the gradient type to `axial` (also known as linear) and sets the start and end points, and optionally the gradient colors and locations.
///
/// - parameter startPoint: The start point of the gradient with (0.0, 0.0) and (1.0, 1.0) representing the top-left and bottom-right corners of the label, respectively. Points whose coordinates lie outside of this range will be clamped
/// - parameter endPoint: The end point of the gradient with (0.0, 0.0) and (1.0, 1.0) representing the top-left and bottom-right corners of the label, respectively. Points whose coordinates lie outside of this range will be clamped
/// - parameter colors: The colors of the gradient
/// - parameter locations: The locations of the gradient colors
/// - parameter options: The gradient drawing options. If unspecified, this defaults to a null option set
@nonobjc open func setAxialGradientParameters(startPoint: CGPoint, endPoint: CGPoint, colors: [UIColor]? = nil, locations: [CGFloat]? = nil, options: CGGradientDrawingOptions = []) {
setAxialGradientParameters(startPoint: startPoint,
endPoint: endPoint,
colors: colors,
locations: locations?.map { NSNumber(value: Double($0)) },
options: options)
}
/// Sets the gradient type to `radial` and sets the start and end cneter points, the start and end radii, and optionally the gradient colors and locations.
///
/// - parameter startCenter: The start center of the gradient with (0.0, 0.0) and (1.0, 1.0) representing the top-left and bottom-right corners of the label, respectively. Points whose coordinates lie outside of this range will be clamped
/// - parameter startRadius: The start radius of the gradient. The expected range of this value is [0.0, 1.0] and any value outside of this range will be clamped.
/// - parameter endCenter: The end center of the gradient with (0.0, 0.0) and (1.0, 1.0) representing the top-left and bottom-right corners of the label, respectively. Points whose coordinates lie outside of this range will be clamped
/// - parameter endRadius: The end radius of the gradient. The expected range of this value is [0.0, 1.0] and any value outside of this range will be clamped.
/// - parameter radiusScalingRule: The rule to use when scaling up the radii from their [0.0, 1.0] range to the coordinate space of the label.
/// - parameter colors: The colors of the gradient
/// - parameter locations: The locations of the gradient colors
/// - parameter options: The gradient drawing options.
@objc open func setRadialGradientParameters(startCenter: CGPoint,
startRadius: CGFloat,
endCenter: CGPoint,
endRadius: CGFloat,
colors: [UIColor]? = nil,
locations: [NSNumber]? = nil,
radiiScalingRule: RadialGradientRadiiScalingRule = .default,
options: CGGradientDrawingOptions = []) {
gradientOptions = options
gradientType = .radial(startCenter: startCenter.clamped(min: 0.0, max: 1.0),
startRadius: startRadius,
endCenter: endCenter.clamped(min: 0.0, max: 1.0),
endRadius: endRadius,
radiiScalingRule: radiiScalingRule)
if let colors = colors { gradientColors = colors }
if let locations = locations { gradientLocations = locations }
super.setNeedsDisplay()
}
/// Sets the gradient type to `radial` and sets the start and end cneter points, the start and end radii, and optionally the gradient colors and locations.
///
/// - parameter startCenter: The start center of the gradient with (0.0, 0.0) and (1.0, 1.0) representing the top-left and bottom-right corners of the label, respectively. Points whose coordinates lie outside of this range will be clamped
/// - parameter startRadius: The start radius of the gradient. The expected range of this value is [0.0, 1.0] and any value outside of this range will be clamped.
/// - parameter endCenter: The end center of the gradient with (0.0, 0.0) and (1.0, 1.0) representing the top-left and bottom-right corners of the label, respectively. Points whose coordinates lie outside of this range will be clamped
/// - parameter endRadius: The end radius of the gradient. The expected range of this value is [0.0, 1.0] and any value outside of this range will be clamped.
/// - parameter radiusScalingRule: The rule to use when scaling up the radii from their [0.0, 1.0] range to the coordinate space of the label. If unspecified, this defaults to `maximumBound`
/// - parameter colors: The colors of the gradient
/// - parameter locations: The locations of the gradient colors
/// - parameter options: The gradient drawing options. If unspecified, this defaults to a null option set
@nonobjc open func setRadialGradientParameters(startCenter: CGPoint,
startRadius: CGFloat,
endCenter: CGPoint,
endRadius: CGFloat,
colors: [UIColor]? = nil,
locations: [CGFloat]? = nil,
radiiScalingRule: RadialGradientRadiiScalingRule = .default,
options: CGGradientDrawingOptions = []) {
setRadialGradientParameters(startCenter: startCenter,
startRadius: startRadius,
endCenter: endCenter,
endRadius: endRadius,
colors: colors,
locations: locations?.map { NSNumber(value: Double($0)) },
radiiScalingRule: radiiScalingRule,
options: options)
}
@objc open func clearGradientParameters() {
gradientType = nil
gradientColors = nil
gradientLocations = nil
gradientOptions = []
super.setNeedsDisplay()
}
// MARK: UIView Overrides
override open func setNeedsDisplay() {
super.setNeedsDisplay()
self.textImage = nil
}
override open func setNeedsDisplay(_ rect: CGRect) {
super.setNeedsDisplay(rect)
self.textImage = nil
}
override open func draw(_ rect: CGRect) {
let size = bounds.size
if textImage == nil {
let drawText = {
let backgroundColor = self.layer.backgroundColor
self.layer.backgroundColor = UIColor.clear.cgColor
super.draw(rect)
self.layer.backgroundColor = backgroundColor
}
if #available(iOS 10.0, tvOS 10.0, *) {
textImage = UIGraphicsImageRenderer(size: size).image { _ in drawText() }
} else {
UIGraphicsBeginImageContext(size)
defer { UIGraphicsEndImageContext() }
drawText()
textImage = UIGraphicsGetImageFromCurrentImageContext()
}
}
if let context = UIGraphicsGetCurrentContext(),
let gradientColors = gradientColors,
let gradientType = gradientType {
var gradient: CGGradient?
if let gradientLocations = gradientLocations {
gradientLocations.map { CGFloat($0.doubleValue) }.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<CGFloat>) in
gradient = CGGradient(colorsSpace: nil, colors: (gradientColors.map { $0.cgColor } as CFArray), locations: buffer.baseAddress)
}
} else {
gradient = CGGradient(colorsSpace: nil, colors: (gradientColors.map { $0.cgColor } as CFArray), locations: nil)
}
if let gradient = gradient {
switch gradientType {
case let .axial(start, end):
context.drawLinearGradient(gradient,
start: CGPoint(x: start.x * size.width, y: start.y * size.height),
end: CGPoint(x: end.x * size.width, y: end.y * size.height),
options: gradientOptions)
case let .radial(startCenter, startRadius, endCenter, endRadius, radiiScalingRule):
let radiiScale: CGFloat
switch radiiScalingRule {
case .width: radiiScale = size.width
case .height: radiiScale = size.height
case .minimumBound: radiiScale = min(size.width, size.height)
case .maximumBound: radiiScale = max(size.width, size.height)
}
context.drawRadialGradient(gradient,
startCenter: CGPoint(x: startCenter.x * size.width, y: startCenter.y * size.height),
startRadius: startRadius * radiiScale,
endCenter: CGPoint(x: endCenter.x * size.width, y: endCenter.y * size.height),
endRadius: endRadius * radiiScale,
options: gradientOptions)
}
}
}
switch textGradientLocation {
case .foreground: textImage?.draw(at: .zero, blendMode: .destinationIn, alpha: 1.0)
case .background: textImage?.draw(at: .zero)
}
}
}
// MARK: - CGPoint Extension
extension CGPoint {
fileprivate func clamped(minX: CGFloat, maxX: CGFloat, minY: CGFloat, maxY: CGFloat) -> CGPoint {
precondition(minX <= maxX, "'minX' must be less than or equal to 'maxX'")
precondition(minY <= maxY, "'minY' must be less than or equal to 'maxY'")
var point = self
if point.x < minX { point.x = minX }
if point.y < minY { point.y = minY }
if point.x > maxX { point.x = maxX }
if point.y > maxY { point.y = maxY }
return point
}
fileprivate func clamped(min: CGPoint, max: CGPoint) -> CGPoint {
return clamped(minX: min.x, maxX: max.x, minY: min.y, maxY: max.y)
}
fileprivate func clamped(min: CGFloat, max: CGFloat) -> CGPoint {
return clamped(minX: min, maxX: max, minY: min, maxY: max)
}
}