簡體   English   中英

使用CoreText繪制時未顯示NSTextAttachment圖像

[英]NSTextAttachment image not showing when drawing using CoreText

出於某種原因,當使用核心文本時,我無法獲得要繪制的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中。

有兩種方法可以解決問題:

  1. 創建UILabel,CATextLayer或類似物,並將其渲染到圖形上下文中。
  2. 使用CTRunDelegate在文本中打孔,然后循環遍歷要渲染的所有行,並手動將圖像直接繪制到CGContext中。 這里有詳細說明: https//www.raywenderlich.com/4147/core-text-tutorial-for-ios-making-a-magazine-app 如果沿着這條路走下去會有很多工作,但它確實有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM