Nuoji
Nuoji

Reputation: 3448

NSTextAttachment image not showing when drawing using CoreText

For some reason I'm unable to get NSTextAttachment images to draw when using core text, although the same image would display fine when the NSAttributedString is added to an UILabel.

On iOS this rendering will give empty spaces for the NSTextAttachments, for OS X, a placeholder [OBJECT] square image is rendered for each NSTextAttachment instead. Is there something else that needs to be done in order to render images with CoreText?

The rendering code:

CGFloat contextHeight = CGBitmapContextGetHeight(context);
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)_attributedString);
CGPathRef path = CGPathCreateWithRect(CGRectMake(rect.origin.x,
                                                 contextHeight - rect.origin.y - rect.size.height,
                                                 rect.size.width,
                                                 rect.size.height), NULL);
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
CFRelease(framesetter);
CGPathRelease(path);
CGContextSaveGState(context);
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0.0f, contextHeight);
CGContextScaleCTM(context, 1.0f, -1.0f);
CTFrameDraw(frame, context);
CGContextRestoreGState(context);
CFRelease(frame);

Upvotes: 4

Views: 1558

Answers (1)

Nuoji
Nuoji

Reputation: 3448

The reason is simply that NSTextAttachment only works for rendering a NSAttributedString into an UIView/NSView. It can't be used to render into a regular CGContext.

There are two possible ways to solve the problem:

  1. Create a UILabel, CATextLayer or similar, and render it into the graphics context.
  2. Use CTRunDelegate to punch spaces in the text, then loop through all the lines to be rendered and draw the images directly into the CGContext manually. The way to do it is detailed here: https://www.raywenderlich.com/4147/core-text-tutorial-for-ios-making-a-magazine-app. Expect a lot of work if you go down this route, but it works.

Upvotes: 6

Related Questions