Mostrar nsattributedstring usando coretext
-
26-10-2019 - |
Pregunta
He oído que puedo mostrar un nsattributedstring usando Coreteext, ¿alguien puede decirme cómo (la forma más sencilla)?
Por favor, no responda con Catextlayer o OhattributeDLabel.
Sé que hay muchas preguntas sobre esto en este foro, pero no he encontrado la respuesta.
¡¡Gracias!!
Solución
Creo que la forma más simple (usando texto central) es:
// 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);
El uso de un FrameSetter es más eficiente si está dibujando mucho texto, pero este es el método recomendado por Apple si solo necesita mostrar una pequeña cantidad de texto (como una etiqueta) y no requiere que cree una ruta o marco ( ya que está hecho por usted automáticamente por CTLineDraw
).
Otros consejos
Más simple forma? Algo como esto:
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);
A partir de iOS 6 puedes hacer lo siguiente:
NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init];
[paragrahStyle setLineSpacing:40];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragrahStyle range:NSMakeRange(0, [labelText length])];
cell.label.attributedText = attributedString ;