Show NSAttributedString using CoreText

I heard that I can show NSAttributedString using CoreText, can anyone tell me how (The easiest way)?

Please do not respond with CATextLayer or OHAttributedLabel.

I know there are a lot of questions on this forum, but I did not find the answer

Thanks!!

+6
source share
3 answers

I think the easiest way (using 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); 

Using Framesetter is more efficient if you draw a lot of text, but this is the method recommended by Apple, if you just need to display a small amount of text (for example, a label) and does not require creating a path or frame (since this is done for you automatically using CTLineDraw ) .

+10
source

The easiest way? Something like that:

 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); 
+12
source

Starting with ios 6 you can do the following:

  NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init]; [paragrahStyle setLineSpacing:40]; [attributedString addAttribute:NSParagraphStyleAttributeName value:paragrahStyle range:NSMakeRange(0, [labelText length])]; cell.label.attributedText = attributedString ; 
+1
source

Source: https://habr.com/ru/post/902727/


All Articles