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

Nuo*_*oji 4 macos core-text ios

出于某种原因,当使用核心文本时,我无法获得要绘制的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);
Run Code Online (Sandbox Code Playgroud)

Nuo*_*oji 5

原因很简单,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.如果沿着这条路走下去会有很多工作,但它确实有效.

  • `CATextLayer` 不支持 `NSTextAttachment`。使用 `-[NSAttributedString drawInRect:]` 绘制到普通的 `CALayer` 中确实会呈现附件。 (2认同)