Skip to content

Instantly share code, notes, and snippets.

@odrobnik
Last active February 21, 2023 12:06
Show Gist options
  • Save odrobnik/2751fb3ce32792b8a85d to your computer and use it in GitHub Desktop.
Save odrobnik/2751fb3ce32792b8a85d to your computer and use it in GitHub Desktop.
Swift: create CGPath from attributed string
func appendToPath(path: CGMutablePath)
{
let textPath = CGPathCreateMutable()
let attributedString = NSAttributedString(string: string)
let line = CTLineCreateWithAttributedString(attributedString)
// direct cast to typed array fails for some reason
let runs = (CTLineGetGlyphRuns(line) as [AnyObject]) as! [CTRun]
for run in runs
{
let attributes: NSDictionary = CTRunGetAttributes(run)
let font = attributes[kCTFontAttributeName as String] as! CTFont
let count = CTRunGetGlyphCount(run)
for index in 0..<count
{
let range = CFRangeMake(index, 1)
var glyph = CGGlyph()
CTRunGetGlyphs(run, range, &glyph)
var position = CGPoint()
CTRunGetPositions(run, range, &position)
let letterPath = CTFontCreatePathForGlyph(font, glyph, nil)
var transform = CGAffineTransformMake(1, 0, 0, -1, position.x, position.y)
CGPathAddPath(textPath, &transform, letterPath)
}
}
var transform = CGAffineTransformMakeTranslation(location.x, location.y)
CGPathAddPath(path, &transform, textPath)
}
@ljs19923
Copy link

ljs19923 commented Nov 19, 2018

What's location.x and location.y ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment