简体   繁体   中英

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM