由于某种原因, 当使用 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);
CATextLayer
不支持NSTextAttachment
。使用-[NSAttributedString drawInRect:]
在普通的CALayer
中绘制可以呈现附件。 - Ortwin Gentz