forked from tobihagemann/THLabel
/
THLabel.swift
853 lines (779 loc) · 35.1 KB
/
THLabel.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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
//
// THLabel.swift
//
// Version 1.4.8
//
// Created by Vitalii Parovishnyk on 01/12/17.
// Copyright (c) 2018 IGR Software. All rights reserved.
//
// Original source and inspiration from:
// FXLabel by Nick Lockwood,
// https://github.com/nicklockwood/FXLabel
// KSLabel by Kai Schweiger,
// https://github.com/vigorouscoding/KSLabel
// GTMFadeTruncatingLabel by Google,
// https://github.com/google/google-toolbox-for-mac/tree/master/iPhone
//
// Big thanks to Jason Miller for showing me sample code of his implementation
// using Core Text! It inspired me to dig deeper and move away from drawing
// with NSAttributedString on iOS 7, which caused a lot of problems.
//
// Distributed under the permissive zlib license
// Get the latest version from here:
//
// https://github.com/tobihagemann/THLabel
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
import UIKit
import Foundation
import CoreFoundation
import CoreText
import CoreGraphics
public enum THLabelStrokePosition : Int {
case outside
case center
case inside
}
public struct THLabelFadeTruncatingMode : OptionSet {
public let rawValue: Int
public init(rawValue:Int) { self.rawValue = rawValue}
static let none = THLabelFadeTruncatingMode(rawValue: 0)
static let tail = THLabelFadeTruncatingMode(rawValue: 1 << 0)
static let head = THLabelFadeTruncatingMode(rawValue: 1 << 1)
static let headAndTail : THLabelFadeTruncatingMode = [.tail, .head]
}
open
class THLabel: UILabel {
// MARK: - Accessors and Mutators
open var letterSpacing: CGFloat = 0.0
open var lineSpacing: CGFloat = 0.0
private var _shadowBlur: CGFloat = 0.0
open var shadowBlur: CGFloat {
get {
return _shadowBlur
}
set {
_shadowBlur = CGFloat(fmaxf(Float(newValue), 0.0))
}
}
open var innerShadowBlur: CGFloat = 0.0
open var innerShadowOffset: CGSize = CGSize.zero
open var innerShadowColor: UIColor!
open var strokeSize: CGFloat = 0.0
open var strokeColor: UIColor!
open var strokePosition: THLabelStrokePosition = THLabelStrokePosition.outside
open var gradientStartColor: UIColor! {
get {
return self.gradientColors.count > 0 ? self.gradientColors.first! : nil
}
set {
if newValue == nil {
self.gradientColors = []
}
else if self.gradientColors.count < 2 {
self.gradientColors = [newValue, newValue]
}
else if !self.gradientColors.first!.isEqual(newValue) {
var colors = self.gradientColors
colors[0] = newValue
self.gradientColors = colors
}
}
}
open var gradientEndColor: UIColor! {
get {
return self.gradientColors.count > 0 ? self.gradientColors.last! : nil
}
set {
if newValue == nil {
self.gradientColors = []
}
else if self.gradientColors.count < 2 {
self.gradientColors = [newValue, newValue]
}
else if !self.gradientColors.last!.isEqual(newValue) {
var colors = self.gradientColors
colors[colors.count - 1] = newValue
self.gradientColors = colors
}
}
}
private var _gradientColors : [UIColor] = []
open var gradientColors : [UIColor] {
get {
return _gradientColors
}
set {
if _gradientColors != newValue {
_gradientColors = newValue
self.setNeedsDisplay()
}
}
}
open var gradientStartPoint: CGPoint = CGPoint.zero
open var gradientEndPoint: CGPoint = CGPoint.zero
open var fadeTruncatingMode: THLabelFadeTruncatingMode = THLabelFadeTruncatingMode.none
private var _textInsets : UIEdgeInsets = UIEdgeInsets.zero
open var textInsets : UIEdgeInsets {
get {
return _textInsets
}
set {
if !UIEdgeInsetsEqualToEdgeInsets(_textInsets, newValue) {
_textInsets = newValue
self.setNeedsDisplay()
}
}
}
open var isAutomaticallyAdjustTextInsets: Bool = false
override public init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
self.setDefaults()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setDefaults()
}
fileprivate func setDefaults() {
self.clipsToBounds = true
self.gradientStartPoint = CGPoint(x:0.5, y: 0.2)
self.gradientEndPoint = CGPoint(x: 0.5, y: 0.8)
self.isAutomaticallyAdjustTextInsets = true
}
fileprivate func hasShadow() -> Bool {
return self.shadowColor != nil && !self.shadowColor!.isEqual(UIColor.clear) && (self.shadowBlur > 0.0 || !self.shadowOffset.equalTo(CGSize.zero))
}
fileprivate func hasInnerShadow() -> Bool {
return (self.innerShadowColor != nil) && !self.innerShadowColor.isEqual(UIColor.clear) && (self.innerShadowBlur > 0.0 || !self.innerShadowOffset.equalTo(CGSize.zero))
}
fileprivate func hasStroke() -> Bool {
return self.strokeSize > 0.0 && !self.strokeColor.isEqual(UIColor.clear)
}
fileprivate func hasGradient() -> Bool {
return self.gradientColors.count > 1
}
fileprivate func hasFadeTruncating() -> Bool {
return self.fadeTruncatingMode != THLabelFadeTruncatingMode.none
}
override open func sizeThatFits(_ size: CGSize) -> CGSize {
return self.intrinsicContentSize
}
override open var intrinsicContentSize: CGSize {
get {
if self.text == nil || (self.text == "") {
return CGSize.zero
}
let textRect = self.frameRef(from: CGSize(width: CGFloat(self.preferredMaxLayoutWidth), height: CGFloat.greatestFiniteMagnitude)).CGRect
let newWidth = textRect.width + self.textInsets.left + self.textInsets.right
let newHeight = textRect.height + self.textInsets.top + self.textInsets.bottom
return CGSize(width: CGFloat(ceilf(Float(newWidth))), height: CGFloat(ceilf(Float(newHeight))))
}
}
fileprivate func strokeSizeDependentOnStrokePosition() -> CGFloat {
switch self.strokePosition {
case .center:
return self.strokeSize
default:
// Stroke width times 2, because CG draws a centered stroke. We cut the rest into halves.
return self.strokeSize * 2.0
}
}
// MARK: - Drawing
// override open func draw(_ rect: CGRect) {
// // Don't draw anything, if there is no text.
// if self.text == nil || (self.text == "") {
// return
// }
// // -------
// // Determine what has to be drawn.
// // -------
// let hasShadow = self.hasShadow()
// let hasInnerShadow = self.hasInnerShadow()
// let hasStroke = self.hasStroke()
// let hasGradient = self.hasGradient()
// let hasFadeTruncating = self.hasFadeTruncating()
// let needsMask = hasGradient || (hasStroke && self.strokePosition == .inside) || hasInnerShadow
// // -------
// // Step 1: Begin new drawing context, where we will apply all our styles.
// // -------
// UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
// let context = UIGraphicsGetCurrentContext()!
// var alphaMask: CGImage? = nil
// let frame = self.frameRef(from: self.bounds.size)
// let textRect = frame.CGRect
// let frameRef = frame.CTFrame
// // Invert everything, because CG works with an inverted coordinate system.
// context.translateBy(x: 0.0, y: rect.height)
// context.scaleBy(x: 1.0, y: -1.0)
// // -------
// // Step 2: Prepare mask.
// // -------
// if needsMask {
// context.saveGState()
// // Draw alpha mask.
// context.setTextDrawingMode(.fill)
// UIColor.white.setFill()
// CTFrameDraw(frameRef, context)
// // Save alpha mask.
// alphaMask = context.makeImage()
// // Clear the content.
// context.clear(rect)
// context.restoreGState()
// }
// // -------
// // Step 3: Draw text normally, or with gradient.
// // -------
// context.saveGState()
// if !hasGradient {
// // Draw text.
// context.setTextDrawingMode(.fill)
// CTFrameDraw(frameRef, context)
// }
// else {
// // Clip the current context to alpha mask.
// context.clip(to: rect, mask: alphaMask!)
// // Invert back to draw the gradient correctly.
// context.translateBy(x: 0.0, y: rect.height)
// context.scaleBy(x: 1.0, y: -1.0)
// // Get gradient colors as CGColor.
// var gradientColors = [CGColor]() /* capacity: self.gradientColors.count */
// for color: UIColor in self.gradientColors {
// gradientColors.append(color.cgColor)
// }
// // Create gradient.
// let colorSpace = CGColorSpaceCreateDeviceRGB()
// let gradient = CGGradient(colorsSpace: colorSpace, colors: (gradientColors as CFArray), locations: nil)
// let startPoint = CGPoint(x: CGFloat(textRect.origin.x + self.gradientStartPoint.x * textRect.width), y: CGFloat(textRect.origin.y + self.gradientStartPoint.y * textRect.height))
// let endPoint = CGPoint(x: CGFloat(textRect.origin.x + self.gradientEndPoint.x * textRect.width), y: CGFloat(textRect.origin.y + self.gradientEndPoint.y * textRect.height))
// // Draw gradient.
// context.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: [.drawsBeforeStartLocation , .drawsAfterEndLocation])
// // Clean up.
// }
// context.restoreGState()
// // -------
// // Step 4: Draw inner shadow.
// // -------
// if hasInnerShadow {
// context.saveGState()
// // Clip the current context to alpha mask.
// context.clip(to: rect, mask: alphaMask!)
// // Invert to draw the inner shadow correctly.
// context.translateBy(x: 0.0, y: rect.height)
// context.scaleBy(x: 1.0, y: -1.0)
// // Draw inner shadow.
// let shadowImage = self.inverseMask(fromAlphaMask: alphaMask!, with: rect)
// context.setShadow(offset: self.innerShadowOffset, blur: self.innerShadowBlur, color: self.innerShadowColor.cgColor)
// context.setBlendMode(.darken)
// context.draw(shadowImage, in: rect)
// // Clean up.
// context.restoreGState()
// }
//
// // -------
// // Step 5: Draw stroke.
// // -------
// if hasStroke {
// context.saveGState()
// context.setTextDrawingMode(.stroke)
// var image: CGImage? = nil
// if self.strokePosition == .outside {
// // Create an image from the text.
// image = context.makeImage()
// }
// else if self.strokePosition == .inside {
// // Clip the current context to alpha mask.
// context.clip(to: rect, mask: alphaMask!)
// }
//
// // Draw stroke.
// let strokeImage = self.strokeImage(with: rect, frameRef: frameRef, strokeSize: self.strokeSizeDependentOnStrokePosition(), stroke: self.strokeColor)
// context.draw(strokeImage, in: rect)
// if self.strokePosition == .outside {
// // Draw the saved image over half of the stroke.
// context.draw(image!, in: rect)
// }
// // Clean up.
// context.restoreGState()
// }
//
// // -------
// // Step 6: Draw strike through.
// // -------
//
// if let attributedString = self.attributedText {
// let attr = attributedString.attributes(at: 0, effectiveRange: nil)
// if attr[.strikethroughStyle] != nil {
// // reset text position
// context.textPosition = .zero
//
// // get lines
// let lines = CTFrameGetLines(frameRef) as NSArray
// var origins: [CGPoint] = [CGPoint](repeating: CGPoint.zero, count: lines.count)
// CTFrameGetLineOrigins(frameRef,
// CFRangeMake(0, 0), &origins)
//
// var lineIndex = 0
//
// for oneLine in lines {
// let runs = CTLineGetGlyphRuns(oneLine as! CTLine) as NSArray
// var lineBounds = CTLineGetImageBounds(oneLine as! CTLine, context)
//
// lineBounds.origin.x += origins[lineIndex].x
// lineBounds.origin.y += origins[lineIndex].y
// lineIndex += 1
// var offset: CGFloat = 0
//
// for oneRun in runs {
// var ascent: CGFloat = 0
// var descent: CGFloat = 0
//
// let width: CGFloat = CGFloat(CTRunGetTypographicBounds(oneRun as! CTRun,
// CFRangeMake(0, 0),
// &ascent,
// &descent, nil))
//
// let attributes = CTRunGetAttributes(oneRun as! CTRun) as NSDictionary
// var bounds = CGRect(x: lineBounds.origin.x + offset,
// y: lineBounds.origin.y,
// width: width,
// height: ascent + descent);
//
// // don't draw too far to the right
// if bounds.origin.x + bounds.size.width > lineBounds.maxX {
// bounds.size.width = lineBounds.maxX - bounds.origin.x
// }
//
// // get text color or use black
// if let color = attributes.object(forKey: kCTForegroundColorAttributeName) {
// context.setStrokeColor(color as! CGColor)
// }
// else {
// context.setStrokeColor(UIColor.white.cgColor)
// }
//
// let y = bounds.origin.y + bounds.height / 2 + textInsets.top
// context.move(to: CGPoint(x: bounds.origin.x, y: y))
// context.addLine(to: CGPoint(x: bounds.origin.x + bounds.width, y: y))
// context.strokePath()
// offset += width
// }
// }
// }
// }
//
// // -------
// // Step 7: Draw shadow.
// // -------
// if hasShadow {
// context.saveGState()
// // Create an image from the text.
// let image = context.makeImage()
// // Clear the content.
// context.clear(rect)
// // Set shadow attributes.
// context.setShadow(offset: self.shadowOffset, blur: self.shadowBlur, color: self.shadowColor!.cgColor)
// // Draw the saved image, which throws off a shadow.
// context.draw(image!, in: rect)
// // Clean up.
// context.restoreGState()
// }
//
// // -------
// // Step 8: Draw fade truncating.
// // -------
// if hasFadeTruncating {
// context.saveGState()
// // Create an image from the text.
// let image = context.makeImage()
// // Clear the content.
// context.clear(rect)
// // Clip the current context to linear gradient mask.
// let linearGradientImage = self.linearGradientImage(with: rect, fadeHead: self.fadeTruncatingMode.contains(.head), fadeTail: self.fadeTruncatingMode.contains(.tail))
// context.clip(to: self.bounds, mask: linearGradientImage)
// // Draw the saved image, which is clipped by the linear gradient mask.
// context.draw(image!, in: rect)
// // Clean up.
// context.restoreGState()
// }
//
// // -------
// // Step 9: End drawing context and finally draw the text with all styles.
// // -------
// let image = UIGraphicsGetImageFromCurrentImageContext()!
// UIGraphicsEndImageContext()
// image.draw(in: rect)
// }
func drawStroke(_ rect: CGRect, context: CGContext) {
var alphaMask: CGImage? = nil
let hasInnerShadow = self.hasInnerShadow()
let hasStroke = self.hasStroke()
let hasGradient = self.hasGradient()
let needsMask = hasGradient || (hasStroke && self.strokePosition == .inside) || hasInnerShadow
let frameRef: CTFrame
if hasStroke && strokePosition == .outside {
var frame = self.bounds.size
frame.width += strokeSizeDependentOnStrokePosition()
frame.height += strokeSizeDependentOnStrokePosition()
frameRef = self.frameRef(from: frame).CTFrame
}
else {
let cframe = self.frameRef(from: self.bounds.size)
frameRef = cframe.CTFrame
}
// -------
// Step 2: Prepare mask.
// -------
if needsMask {
context.saveGState()
// Draw alpha mask.
context.setTextDrawingMode(.fill)
UIColor.white.setFill()
CTFrameDraw(frameRef, context)
// Save alpha mask.
alphaMask = context.makeImage()
// Clear the content.
context.clear(rect)
context.restoreGState()
}
if hasStroke {
context.saveGState()
context.setTextDrawingMode(.stroke)
var image: CGImage? = nil
if self.strokePosition == .outside {
// Create an image from the text.
image = context.makeImage()
}
else if self.strokePosition == .inside {
// Clip the current context to alpha mask.
context.clip(to: rect, mask: alphaMask!)
}
if self.strokePosition == .outside {
var frame = rect
frame.size.width += strokeSizeDependentOnStrokePosition()
frame.size.height += strokeSizeDependentOnStrokePosition()
// Draw stroke.
let strokeImage = self.strokeImage(with: frame, frameRef: frameRef, strokeSize: self.strokeSizeDependentOnStrokePosition(), stroke: self.strokeColor)
context.draw(strokeImage, in: rect)
// Draw the saved image over half of the stroke.
context.draw(image!, in: rect)
}
else {
// Draw stroke.
let strokeImage = self.strokeImage(with: rect, frameRef: frameRef, strokeSize: self.strokeSizeDependentOnStrokePosition(), stroke: self.strokeColor)
context.draw(strokeImage, in: rect)
}
// Clean up.
context.restoreGState()
}
}
func drawShadow(_ rect: CGRect, context: CGContext) {
// -------
// Step 7: Draw shadow.
// -------
let hasShadow = self.hasInnerShadow()
if hasShadow {
context.saveGState()
// Create an image from the text.
let image = context.makeImage()
// Clear the content.
context.clear(rect)
// Set shadow attributes.
context.setShadow(offset: self.innerShadowOffset, blur: self.innerShadowBlur, color: self.innerShadowColor.cgColor)
// Draw the saved image, which throws off a shadow.
context.draw(image!, in: rect)
// Clean up.
context.restoreGState()
}
}
open override func draw(_ rect: CGRect) {
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
let context = UIGraphicsGetCurrentContext()!
context.translateBy(x: 0.0, y: rect.height)
context.scaleBy(x: 1.0, y: -1.0)
drawStroke(rect, context: context)
context.translateBy(x: 0.0, y: rect.height)
context.scaleBy(x: 1.0, y: -1.0)
super.drawText(in: rect)
context.translateBy(x: 0.0, y: rect.height)
context.scaleBy(x: 1.0, y: -1.0)
drawShadow(rect, context: context)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
image.draw(in: rect)
}
fileprivate func frameRef(from size: CGSize) -> (CTFrame: CTFrame, CGRect: CGRect) {
// Set up font.
var alignment = NSTextAlignmentToCTTextAlignment(self.textAlignment)
var lineBreakMode = CTLineBreakModeFromUILineBreakMode(self.lineBreakMode)
var lineSpacing = self.lineSpacing
let paragraphStyleSettings: [CTParagraphStyleSetting] = [
CTParagraphStyleSetting(spec: .alignment, valueSize: MemoryLayout.size(ofValue: alignment), value: &alignment),
CTParagraphStyleSetting(spec: .lineBreakMode, valueSize: MemoryLayout.size(ofValue: lineBreakMode), value: &lineBreakMode),
CTParagraphStyleSetting(spec: .lineSpacingAdjustment, valueSize: MemoryLayout.size(ofValue: lineSpacing), value: &lineSpacing)
]
let paragraphStyleRef = CTParagraphStyleCreate(paragraphStyleSettings, paragraphStyleSettings.count)
let kernRef = CFNumberCreate(kCFAllocatorDefault, .cgFloatType, &letterSpacing)
// Set up attributed string.
let attributedStringRef: CFAttributedString
var literalAttr: [AnyHashable: Any] = [:]
if let attributedString = self.attributedText {
let attr = attributedString.attributes(at: 0, effectiveRange: nil)
if let font = attr[.font] as? UIFont {
let fontRef = CTFontCreateWithName(font.fontName as CFString, font.pointSize, nil)
literalAttr[kCTFontAttributeName] = fontRef
}
literalAttr[kCTForegroundColorAttributeName] = (attr[.foregroundColor] as? UIColor)?.cgColor
literalAttr[kCTKernAttributeName] = kernRef
literalAttr[kCTParagraphStyleAttributeName] = paragraphStyleRef
if let rawValue = attr[.underlineStyle] as? Int, let underlineStyle = NSUnderlineStyle(rawValue: rawValue) {
switch underlineStyle {
case .styleSingle:
literalAttr[kCTUnderlineStyleAttributeName] = CTUnderlineStyle.single.rawValue as CFNumber
case .styleDouble:
literalAttr[kCTUnderlineStyleAttributeName] = CTUnderlineStyle.double.rawValue as CFNumber
case .styleThick:
literalAttr[kCTUnderlineStyleAttributeName] = CTUnderlineStyle.thick.rawValue as CFNumber
case .patternDash:
literalAttr[kCTUnderlineStyleAttributeName] = CTUnderlineStyleModifiers.patternDash.rawValue as CFNumber
case .patternDot:
literalAttr[kCTUnderlineStyleAttributeName] = CTUnderlineStyleModifiers.patternDot.rawValue as CFNumber
case .patternDashDot:
literalAttr[kCTUnderlineStyleAttributeName] = CTUnderlineStyleModifiers.patternDashDot.rawValue as CFNumber
case .patternDashDotDot:
literalAttr[kCTUnderlineStyleAttributeName] = CTUnderlineStyleModifiers.patternDashDotDot.rawValue as CFNumber
default:
break
}
}
literalAttr[kCTUnderlineColorAttributeName] = (attr[.underlineColor] as? UIColor)?.cgColor
}
else {
let fontRef = CTFontCreateWithName(self.font.fontName as CFString, self.font.pointSize, nil)
literalAttr[kCTFontAttributeName] = fontRef
literalAttr[kCTForegroundColorAttributeName] = self.textColor.cgColor
literalAttr[kCTKernAttributeName] = kernRef
literalAttr[kCTParagraphStyleAttributeName] = paragraphStyleRef
}
let attributes: NSDictionary = NSDictionary(dictionary: literalAttr)
let stringRef = self.text! as CFString
attributedStringRef = CFAttributedStringCreate(kCFAllocatorDefault, stringRef, attributes as CFDictionary)
// Set up frame.
let framesetterRef = CTFramesetterCreateWithAttributedString(attributedStringRef)
if self.isAutomaticallyAdjustTextInsets {
self.textInsets = self.fittingTextInsets()
}
let contentRect = self.contentRect(from: size, with: self.textInsets)
let textRect = self.textRect(fromContentRect: contentRect, framesetterRef: framesetterRef)
let pathRef = CGMutablePath()
pathRef.addRect(textRect, transform: .identity)
let frameRef = CTFramesetterCreateFrame(framesetterRef, CFRangeMake(0, self.text!.count), pathRef, nil)
return (frameRef, textRect)
}
fileprivate func contentRect(from size: CGSize, with insets: UIEdgeInsets) -> CGRect {
var contentRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
// Apply insets.
contentRect.origin.x += insets.left
contentRect.origin.y += insets.top
contentRect.size.width -= insets.left + insets.right
contentRect.size.height -= insets.top + insets.bottom
return contentRect
}
fileprivate func textRect(fromContentRect contentRect: CGRect, framesetterRef: CTFramesetter) -> CGRect {
var suggestedTextRectSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetterRef, CFRangeMake(0, self.text!.count), nil, contentRect.size, nil)
if suggestedTextRectSize.equalTo(CGSize.zero) {
suggestedTextRectSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetterRef, CFRangeMake(0, self.text!.count), nil, CGSize(width: CGFloat(CGFloat.greatestFiniteMagnitude), height: CGFloat(CGFloat.greatestFiniteMagnitude)), nil)
}
var textRect = CGRect(x: 0, y: 0, width: CGFloat(ceilf(Float(suggestedTextRectSize.width))), height: CGFloat(ceilf(Float(suggestedTextRectSize.height))))
// Horizontal alignment.
switch self.textAlignment {
case .center:
textRect.origin.x = CGFloat(floorf(Float(contentRect.minX + (contentRect.width - textRect.width) / 2.0)))
case .right:
textRect.origin.x = CGFloat(floorf(Float(contentRect.minX + contentRect.width - textRect.width)))
default:
textRect.origin.x = CGFloat(floorf(Float(contentRect.minX)))
}
// Vertical alignment. Top and bottom are upside down, because of inverted drawing.
switch self.contentMode {
case .top, .topLeft, .topRight:
textRect.origin.y = CGFloat(floorf(Float(contentRect.minY + contentRect.height - textRect.height)))
case .bottom, .bottomLeft, .bottomRight:
textRect.origin.y = CGFloat(floorf(Float(contentRect.minY)))
default:
textRect.origin.y = CGFloat(floorf(Float(contentRect.minY) + floorf(Float((contentRect.height - textRect.height)) / 2.0)))
}
return textRect
}
fileprivate func fittingTextInsets() -> UIEdgeInsets {
let hasShadow = self.hasShadow()
let hasStroke = self.hasStroke()
var edgeInsets = UIEdgeInsets.zero
if hasStroke {
switch self.strokePosition {
case .outside:
edgeInsets = UIEdgeInsetsMake(self.strokeSize, self.strokeSize, self.strokeSize, self.strokeSize)
case .inside:
edgeInsets = UIEdgeInsetsMake(self.strokeSize / 2.0, self.strokeSize / 2.0, self.strokeSize / 2.0, self.strokeSize / 2.0)
default:
break
}
}
if hasShadow {
edgeInsets.top = CGFloat(fmaxf(Float(edgeInsets.top + self.shadowBlur + self.shadowOffset.height), Float(edgeInsets.top)))
edgeInsets.left = CGFloat(fmaxf(Float(edgeInsets.left + self.shadowBlur + self.shadowOffset.width), Float(edgeInsets.left)))
edgeInsets.bottom = CGFloat(fmaxf(Float(edgeInsets.bottom + self.shadowBlur - self.shadowOffset.height), Float(edgeInsets.bottom)))
edgeInsets.right = CGFloat(fmaxf(Float(edgeInsets.right + self.shadowBlur - self.shadowOffset.width), Float(edgeInsets.right)))
}
return edgeInsets
}
// MARK: - Image Functions
fileprivate func inverseMask(fromAlphaMask alphaMask: CGImage, with rect: CGRect) -> CGImage {
// Create context.
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
let context = UIGraphicsGetCurrentContext()!
// Fill rect, clip to alpha mask and clear.
UIColor.white.setFill()
UIRectFill(rect)
context.clip(to: rect, mask: alphaMask)
context.clear(rect)
// Return image.
let image = context.makeImage()
UIGraphicsEndImageContext()
return image!
}
fileprivate func strokeImage(with rect: CGRect, frameRef: CTFrame, strokeSize: CGFloat, stroke strokeColor: UIColor) -> CGImage {
// Create context.
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
let context = UIGraphicsGetCurrentContext()!
context.setTextDrawingMode(.stroke)
// Draw clipping mask.
context.setLineWidth(strokeSize)
context.setLineJoin(.round)
UIColor.white.setStroke()
CTFrameDraw(frameRef, context)
// Save clipping mask.
let clippingMask = context.makeImage()
// Clear the content.
context.clear(rect)
// Draw stroke.
context.clip(to: rect, mask: clippingMask!)
context.translateBy(x: 0.0, y: rect.height)
context.scaleBy(x: 1.0, y: -1.0)
strokeColor.setFill()
UIRectFill(rect)
// Clean up and return image.
let image = context.makeImage()
UIGraphicsEndImageContext()
return image!
}
fileprivate func linearGradientImage(with rect: CGRect, fadeHead: Bool, fadeTail: Bool) -> CGImage {
// Create an opaque context.
UIGraphicsBeginImageContextWithOptions(rect.size, true, 0.0)
let context = UIGraphicsGetCurrentContext()!
// White background will mask opaque, black gradient will mask transparent.
UIColor.white.setFill()
UIRectFill(rect)
// Create gradient from white to black.
let locs : [CGFloat] = [0.0, 1.0]
let components : [CGFloat] = [1.0, 1.0, 0.0, 1.0]
let colorSpace = CGColorSpaceCreateDeviceGray()
let gradient = CGGradient(colorSpace: colorSpace, colorComponents: components, locations: locs, count: 2)!
// Draw head and/or tail gradient.
let fadeWidth: CGFloat = CGFloat(fminf(Float(rect.height * 2.0), floorf(Float(rect.width / 4.0))))
let minX: CGFloat = rect.minX
let maxX: CGFloat = rect.maxX
if fadeTail {
let startX: CGFloat = maxX - fadeWidth
let startPoint = CGPoint(x: startX, y: CGFloat(rect.midY))
let endPoint = CGPoint(x: maxX, y: CGFloat(rect.midY))
context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: [])
}
if fadeHead {
let startX: CGFloat = minX + fadeWidth
let startPoint = CGPoint(x: startX, y: CGFloat(rect.midY))
let endPoint = CGPoint(x: minX, y: CGFloat(rect.midY))
context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: [])
}
// Clean up and return image.
let image = context.makeImage()
UIGraphicsEndImageContext()
return image!
}
func CTLineBreakModeFromUILineBreakMode(_ lineBreakMode: NSLineBreakMode) -> CTLineBreakMode {
switch (lineBreakMode) {
case .byWordWrapping: return .byWordWrapping;
case .byCharWrapping: return .byCharWrapping;
case .byClipping: return .byClipping;
case .byTruncatingHead: return .byTruncatingHead;
case .byTruncatingTail: return .byTruncatingTail;
case .byTruncatingMiddle: return .byTruncatingMiddle;
}
}
}
func croppedAlphaImageFrame(from cgImage: CGImage) -> CGRect {
let height = cgImage.height
let width = cgImage.width
let pixelData = cgImage.dataProvider!.data
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
var minX = width
var minY = height
var maxX: Int = 0
var maxY: Int = 0
//Filter through data and look for non-transparent pixels.
for y in 0..<height {
for x in 0..<width {
let pixelIndex = (width * y + x) * 4 /* 4 for A, R, G, B */
if data[pixelIndex] != 0 { //Alpha value is not zero pixel is not transparent.
if x < minX {
minX = x
}
if x > maxX {
maxX = x
}
if y < minY {
minY = y
}
if y > maxY {
maxY = y
}
}
}
}
return CGRect(x: minX, y: minY, width: maxX-minX, height: maxY-minY)
}
func createARGBBitmapContext(from cgImage: CGImage) -> CGContext? {
let width = cgImage.width
let height = cgImage.height
let bitmapBytesPerRow = width * 4
let bitmapByteCount = bitmapBytesPerRow * height
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapData = malloc(bitmapByteCount)
if bitmapData == nil {
return nil
}
let context = CGContext (data: bitmapData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bitmapBytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)
return context
}
extension CGSize {
func scale(w: CGFloat, h: CGFloat) -> CGSize {
return CGSize(width: width * w, height: height * h)
}
}