Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get CGPath from Text

I'm currently trying to convert a letter and/or multiple of them to a CGPathRef for manually drawing them into a custom UIView. I tried the way over CoreText and Framesetters including this little snippet but it doesn't seem to work.

NSAttributedString *stringToDraw = [[NSAttributedString alloc] initWithString:content
                                                                       attributes:nil];
    
    // now for the actual drawing
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // flip the coordinate system
    
    // draw
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)stringToDraw);
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), NULL, NULL);
    
    return CTFrameGetPath(frame);
like image 936
Tim Specht Avatar asked Oct 23 '25 16:10

Tim Specht


1 Answers

CTFrameGetPath returns the path the circumscribes the CTFrame, not the path generated by drawing the frame. I assume that you're doing the above because you are caching the paths to improve later drawing performance? (Since CTFrame can easily draw itself into a custom view).

If you really want to get CGPath, you need to drill all the way down to the CGGlyph and then use CTFontCreatePathForGlyph. If you just want to quickly redraw text, I'd probably draw this into a CGLayer (not CALayer) with CTFrameDraw for later reuse.

If you still really want the CGPath for the glyphs, take a look at Low-level text rendering. The code you need is in there.

like image 85
Rob Napier Avatar answered Oct 26 '25 08:10

Rob Napier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!