出于某种原因,当使用核心文本时,我无法获得要绘制的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);
解决方法
原因很简单,NSTextAttachment仅适用于将NSAttributedString呈现为UIView / NSView.它不能用于渲染到常规CGContext中.
>创建UILabel,CATextLayer或类似物,并将其渲染到图形上下文中.
>使用CTRunDelegate在文本中打空格,然后循环遍历要渲染的所有行,并手动将图像直接绘制到CGContext中.这里有详细介绍的方法:https://www.raywenderlich.com/4147/core-text-tutorial-for-ios-making-a-magazine-app.如果沿着这条路走下去会有很多工作,但它确实有效.