99import CoreGraphics
1010import CoreText
1111import Foundation
12+ #if os(macOS)
13+ import AppKit
14+ #endif
1215
1316extension CGPath {
1417 func applyA( action: @escaping ( CGPathElement ) -> ( ) ) {
@@ -52,12 +55,20 @@ extension CGPath {
5255
5356extension String {
5457
55- func toPath( font: CTFont ) -> CGPath {
56- let attrs : [ String : AnyObject ] = [ kCTFontAttributeName as String : font]
57- let attString = CFAttributedStringCreate ( nil , self as CFString , attrs as CFDictionary ) !
58+ func toPath( font: CTFont ) -> CGPath ? {
59+ //kCTFontAttributeName
60+ let attributes = [ NSFontAttributeName as String : font]
61+ let attString = CFAttributedStringCreate ( nil , self as CFString , attributes as CFDictionary ) !
5862 let line = CTLineCreateWithAttributedString ( attString)
5963 let glyphRuns = CTLineGetGlyphRuns ( line)
6064
65+ var ascent = CGFloat ( 0 )
66+ var descent = CGFloat ( 0 )
67+ var leading = CGFloat ( 0 )
68+ CTLineGetTypographicBounds ( line, & ascent, & descent, & leading)
69+ let baseline = ascent
70+
71+
6172 let path = CGMutablePath ( )
6273
6374 for idx in 0 ..< CFArrayGetCount ( glyphRuns) {
@@ -70,12 +81,15 @@ extension String {
7081 var position : CGPoint = . zero
7182 CTRunGetGlyphs ( run, glyphRange, & glyph)
7283 CTRunGetPositions ( run, glyphRange, & position)
73- if let glyphPath = CTFontCreatePathForGlyph ( font, glyph, nil ) {
74- let t = CGAffineTransform ( translationX: position. x, y: position. y)
75- path. addPath ( glyphPath, transform: t)
84+ var t = CGAffineTransform . identity
85+ if let glyphPath = CTFontCreatePathForGlyph ( font, glyph, & t) {
86+ let t = CGAffineTransform ( a: 1 , b: 0 , c: 0 , d: - 1 , tx: position. x, ty: baseline)
87+ let t1 = t. translatedBy ( x: 0 , y: baseline)
88+ path. addPath ( glyphPath, transform: t1)
7689 }
7790 }
7891 }
92+
7993 return path
8094 }
8195}
0 commit comments