使用CoreText绘制时未显示NSTextAttachment图像 [英] NSTextAttachment image not showing when drawing using CoreText

查看:590
本文介绍了使用CoreText绘制时未显示NSTextAttachment图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,我在使用核心文本时无法获取要绘制的NSTextAttachment图像,但是当NSAttributedString添加到UILabel时,相同的图像会显示正常。

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.

在iOS上,此渲染将为NSTextAttachments提供空白空间,对于OS X,将为每个NSTextAttachment呈现占位符[OBJECT]方形图像。为了使用CoreText渲染图像,还需要做些什么吗?

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?

渲染代码:

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


推荐答案

原因很简单,NSTextAttachment仅适用于渲染a NSAttributedString进入UIView / NSView。它不能用于渲染到常规CGContext。

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. 创建UILabel,CATextLayer或类似物,并将其渲染到图形上下文中。

  2. 使用CTRunDelegate在文本中打空格,然后循环遍历所有要渲染的线条并手动将图像直接绘制到CGContext中。这里详细介绍了这一点: https://www.raywenderlich.com/4147/core-text-tutorial-for-ios-making-a-magazine-app 。如果沿着这条路走下去会有很多工作,但它确实有效。

  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.

这篇关于使用CoreText绘制时未显示NSTextAttachment图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆