Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display NSAttributedString using CoreText

I have heard that I can display a NSAttributedString using CoreText, can anyone say me how (The simplest way)?

Please, don't answer with CATextLayer or OHAttributedLabel.

I know that there are a lot of questions about this in this forum, but I haven't find the answer

Thanks!!

like image 978
Garoal Avatar asked Nov 30 '11 06:11

Garoal


2 Answers

Simplest way? Something like this:

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);
like image 71
Amy Worrall Avatar answered Oct 09 '22 02:10

Amy Worrall


I think that the simplest way (using Core Text) is:

 // 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);

Using a Framesetter is more efficient IF you are drawing lots of text but this is the method recommended by Apple if you just need to display a small amount of text (like a label) and doesn't require you to create a path or frame (since it is done for you automatically by CTLineDraw).

like image 45
lnafziger Avatar answered Oct 09 '22 02:10

lnafziger