使用CoreText绘制时,NSTextAttachment图像未显示

4

由于某种原因, 当使用 core text 时,我无法将 NSTextAttachment 图像绘制出来,即使同样的图像在 NSAttributedString 添加到 UILabel 中时会正常显示。

在 iOS 上,NSTextAttachments 的渲染将导致空白处,而在 OS X 上,每个 NSTextAttachment 的占位符 [OBJECT] 方形图像都将被渲染。是否还需要做其他事情才能使用 CoreText 渲染图像呢?

渲染代码:

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);
1个回答

6
原因很简单,NSTextAttachment只能用于将NSAttributedString渲染到UIView/NSView中,不能用于渲染到常规CGContext中。
解决该问题有两种可能的方法:
1.创建一个UILabel、CATextLayer或类似的对象,并将其渲染到图形上下文中。
2.使用CTRunDelegate在文本中插入空格,然后循环遍历所有要渲染的行,并手动将图像直接绘制到CGContext中。具体方法可以参考这里:https://www.raywenderlich.com/4147/core-text-tutorial-for-ios-making-a-magazine-app。如果您选择这条路,需要做很多工作,但是它可以解决问题。

2
CATextLayer 不支持 NSTextAttachment。使用 -[NSAttributedString drawInRect:] 在普通的 CALayer 中绘制可以呈现附件。 - Ortwin Gentz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接