我听说可以使用CoreText来显示NSAttributedString,有人能告诉我最简单的方法吗?
请不要用CATextLayer或OHAttributedLabel作为答案。
我知道这个论坛上有很多关于这个问题的提问,但是我还没有找到答案。
谢谢!
我听说可以使用CoreText来显示NSAttributedString,有人能告诉我最简单的方法吗?
请不要用CATextLayer或OHAttributedLabel作为答案。
我知道这个论坛上有很多关于这个问题的提问,但是我还没有找到答案。
谢谢!
最简单的方法?类似这样:
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);
我认为最简单的方法(使用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
。
iOS 6 开始,您可以执行以下操作:
NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init];
[paragrahStyle setLineSpacing:40];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragrahStyle range:NSMakeRange(0, [labelText length])];
cell.label.attributedText = attributedString ;