gpt4 book ai didi

ios - 使用 CoreText 绘制时不显示 NSTextAttachment 图像

转载 作者:可可西里 更新时间:2023-11-01 05:33:07 27 4
gpt4 key购买 nike

由于某些原因,我无法在使用核心文本时获取 NSTextAttachment 图像来绘制,尽管将 NSAttributedString 添加到 UILabel 时相同的图像可以正常显示。

在 iOS 上,此渲染将为 NSTextAttachment 提供空白空间,对于 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。

有两种可能的方法来解决这个问题:

  1. 创建一个 UILabel、CATextLayer 或类似的,并将其渲染到图形上下文中。
  2. 使用 CTRunDelegate 在文本中打出空格,然后遍历所有要渲染的行并手动将图像直接绘制到 CGContext 中。此处详细介绍了执行此操作的方法:https://www.raywenderlich.com/4147/core-text-tutorial-for-ios-making-a-magazine-app .如果您沿着这条路走下去,预计会有很多工作要做,但它确实有效。

关于ios - 使用 CoreText 绘制时不显示 NSTextAttachment 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36071205/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com