使用CoreText显示NSAttributedString

8

我听说可以使用CoreText来显示NSAttributedString,有人能告诉我最简单的方法吗?

请不要用CATextLayer或OHAttributedLabel作为答案。

我知道这个论坛上有很多关于这个问题的提问,但是我还没有找到答案。

谢谢!


2
如果您不想使用这些包装器,请查看其内部工作原理。 - vikingosegundo
3个回答

13

最简单的方法?类似这样:

CGContextRef context = UIGraphicsGetCurrentContext();

// Flip the coordinate system
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);

// Create a path to render text in
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, self.bounds );

// An attributed string containing the text to render
NSAttributedString* attString = [[NSAttributedString alloc]
                                  initWithString:...];

// create the framesetter and render text
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attString); 
CTFrameRef frame = CTFramesetterCreateFrame(framesetter,
                         CFRangeMake(0, [attString length]), path, NULL);

CTFrameDraw(frame, context);

// Clean up
CFRelease(frame);
CFRelease(path);
CFRelease(framesetter);

你觉得这个怎么样? https://stackoverflow.com/questions/55799043/how-to-properly-compensate-cgcontextref-coordinate-system-so-the-origin-is-at-t - nrudnyk

10

我认为最简单的方法(使用Core Text)是:

 // Create the CTLine with the attributed string
 CTLineRef line = CTLineCreateWithAttributedString(attrString); 

 // Set text position and draw the line into the graphics context called context
 CGContextSetTextPosition(context, x,  y);
 CTLineDraw(line, context);

 // Clean up
 CFRelease(line);

如果你需要绘制大量文本,使用Framesetter是更高效的方法。但是如果你只需要显示少量文本(例如标签),并且不需要创建路径或帧(因为它会自动为你完成),那么这种方法是苹果推荐的方法,你应该使用CTLineDraw


这会在用户创建的任意上下文中呈现该行吗(使用位图数据),还是上下文必须是当前上下文? - Deepak Sharma
@DeepakSharma 这将呈现给用户创建的上下文(在这种情况下,我只是称其为context)。 - lnafziger

0

iOS 6 开始,您可以执行以下操作:

    NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init];
[paragrahStyle setLineSpacing:40];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragrahStyle range:NSMakeRange(0, [labelText length])];

cell.label.attributedText = attributedString ;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接