8

我听说我可以使用 CoreText 显示 NSAttributedString,谁能告诉我如何(最简单的方法)?

请不要用 CATextLayer 或 OHAttributedLabel 回答。

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

谢谢!!

4

3 回答 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);
于 2011-11-30T11:05:03.733 回答
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 会更有效,但这是 Apple 推荐的方法,如果您只需要显示少量文本(如标签)并且不需要您创建路径或框架(因为它是由 自动为您完成的CTLineDraw

于 2012-03-11T17:28:47.960 回答
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 ;
于 2013-04-12T05:32:19.153 回答