-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTextShape.swift
76 lines (61 loc) · 2.21 KB
/
TextShape.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
//
// TextShape.swift
// Jikoku
//
// Created by Raphaël Calabro on 28/08/2017.
// Copyright © 2017 Raphaël Calabro. All rights reserved.
//
import Foundation
import Melisse
#if os(iOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
class TextShape : Shape {
let text: String
#if os(iOS)
let font: UIFont
init(text: String = "", font: UIFont? = nil) {
self.text = text
self.font = font ?? UIFont.systemFont(ofSize: 12)
}
#elseif os(macOS)
let font: NSFont
init(text: String = "", font: NSFont? = nil) {
self.text = text
self.font = font ?? NSFont.systemFont(ofSize: 12)
}
#endif
override var hashValue: Int {
return "text \(text)".hashValue
}
override func addPath(in rectangle: CGRect, to context: CGContext) {
let font = self.font.withSize(min(rectangle.size.width, rectangle.size.height))
var unichars = [UniChar](text.utf16)
var glyphs = [CGGlyph](repeating: 0, count: unichars.count)
let gotGlyphs = CTFontGetGlyphsForCharacters(font as CTFont, &unichars, &glyphs, unichars.count)
if gotGlyphs {
for glyph in glyphs {
var origin = rectangle.origin
if let cgPath = CTFontCreatePathForGlyph(font as CTFont, glyph, nil) {
let bounds = cgPath.boundingBox
origin = CGPoint(x: origin.x + (rectangle.size.width - bounds.width) / 2 - bounds.origin.x, y: origin.y + rectangle.size.height - (rectangle.size.height - bounds.height) / 2 + bounds.origin.y)
}
var transform = CGAffineTransform(scaleX: 1, y: -1).translatedBy(x: origin.x, y: -origin.y)
if let cgPath = CTFontCreatePathForGlyph(font as CTFont, glyph, &transform) {
context.addPath(cgPath)
}
}
}
}
static func ==(lhs: TextShape, rhs: TextShape) -> Bool {
return lhs.text == rhs.text
&& lhs.font == rhs.font
}
}
extension String {
func shape(font: UIFont? = nil) -> TextShape {
return TextShape(text: self, font: font)
}
}