Pregunta

Necesito dibujar texto en un CGContext y desea usar CateXTlayer para configurar el texto. ¿Alguien puede darme algunos pasos en cuanto a cómo se hará? He escrito un código para ello, pero no sé la corrección de ello (ya que soy nuevo en el desarrollo del iPhone).

algunas preguntas básicas: 1. Cómo obtener la posición y el tamaño del texto para configurar el marco de CatexTlayer 2. El texto está saliendo de alguna manera invertido, que he fijado usando CGAffinetransform, pero es un arreglo de hacky y quiero saber la razón real por la que el texto sale invertido. 3. También necesito configurar el ancho de borde del texto y el color para el que estoy usando NSATtributedString, pero la configuración del tamaño del texto (aumento o disminución) no se refleja en la pantalla.

Editar 1:

He actualizado el código según sus recomendaciones, pero el texto no está cambiando incluso después de usar CTFONTREF. Además, en el iPhone, el texto se está truncando un poco de la parte superior. ¿Alguna idea de lo que está siendo incorrectamente? Cuando revisé los valores que estoy obteniendo de gettypohrographicebounds, todos son 0 (origen.x, origen.y, ancho y altura).

El método GetTypoGragographicBounds:

width = CTLineGetTypographicBounds(m_line, &ascent, &descent, &leading);

// Return text bounds
return CGRectMake(0, 0, width, ascent + descent);

El código modificado:

CATextLayer*    text      = [[CATextLayer alloc] init];
CGColorSpaceRef rgbColor  = CGColorSpaceCreateDeviceRGB();
CGColorRef rgb            = CGColorCreate(rgbColor, m_fill_color);
text.foregroundColor      = rgb;
text.frame                = CGRectMake([self getTypographicBounds].origin.x, [self getTypographicBounds].origin.y, [self getTypographicBounds].size.width + 2*m_padding, [self getTypographicBounds].size.height + 2*m_padding);
text.wrapped              = YES;

    NSMutableDictionary *stringAttributes = [NSMutableDictionary dictionary];

    CTFontRef aCFFont = CTFontCreateWithName ((CFStringRef)m_font_name, 30.0, NULL);

    // Set a negative width so we get both stroke and fill to show
    [stringAttributes setObject: (NSObject*)aCFFont forKey: (id)kCTFontNameAttribute];
    [stringAttributes setObject: [NSNumber numberWithFloat: -3 ] forKey: (id)kCTStrokeWidthAttributeName];
    [stringAttributes setObject: [UIColor whiteColor] forKey: (id)kCTStrokeColorAttributeName];

    NSAttributedString *stringToDraw = [[NSAttributedString alloc] initWithString:m_text
                                                                       attributes:stringAttributes];

    text.string = (NSString*)stringToDraw;
    [text drawInContext:ctx];

Editar 2: El ejemplo de Wiki usa CTLIN, estoy usando Catextlayer. Razón :: Catextlayer me permite modificar el texto durante el tiempo de ejecución para mostrar chino, japonés, hindi, ruso y todos los idiomas con diferentes scripts. Además, Catextlayer parece representar con más claridad que CORETEXT.

El problema que enfrento en este momento es que el texto que se muestra en la línea [Text DRAWINGONTXTX: CTX] se trunca desde la parte superior. Revisé el marco y el tamaño de la fuente de texto. El tamaño de la fuente es de 16 px y la altura del marco es de 17.768, por lo que no sé por qué está truncando.

// Ensure CTLine is up-to-date
if (m_is_dirty)
    [self recomputeLine];

// Get text metrics
CGFloat width;
CGFloat ascent;
CGFloat descent;
CGFloat leading;

width = CTLineGetTypographicBounds(m_line, &ascent, &descent, &leading);

// Position text so that top of text aligns with top of layer
CGContextSetTextMatrix(ctx, CGAffineTransformIdentity );

// Setup text drawing style
CGContextSetRGBFillColor   (ctx, m_fill_color  [0], m_fill_color  [1], m_fill_color  [2], 1.0);
CGContextSetRGBStrokeColor (ctx, m_stroke_color[0], m_stroke_color[1], m_stroke_color[2], 1.0);
CGContextSetFont           (ctx, m_font        );
CGContextSetFontSize       (ctx, m_font_size   );
CGContextSetLineWidth      (ctx, m_stroke_width);

CATextLayer*    text      = [[CATextLayer alloc] init];
CGColorSpaceRef rgbColor  = CGColorSpaceCreateDeviceRGB();
CGColorRef rgb            = CGColorCreate(rgbColor, m_fill_color);
text.foregroundColor      = rgb;
text.fontSize = m_font_size;
text.font = m_font;
text.frame                = CGRectMake([self getTypographicBounds].origin.x, [self getTypographicBounds].origin.y, [self getTypographicBounds].size.width, [self getTypographicBounds].size.height);
text.wrapped              = YES;

NSMutableDictionary *stringAttributes = [NSMutableDictionary dictionary];


// Set a negative width so we get both stroke and fill to show
[stringAttributes setObject: [UIFont fontWithName:m_font_name size:m_font_size] forKey: (id)kCTFontNameAttribute];
[stringAttributes setObject: [NSNumber numberWithFloat: -3 ] forKey: (id)kCTStrokeWidthAttributeName];
[stringAttributes setObject: [UIColor whiteColor] forKey: (id)kCTStrokeColorAttributeName];

NSAttributedString *stringToDraw = [[NSAttributedString alloc] initWithString:m_text
                                                                       attributes:stringAttributes];

text.string = (NSString*)stringToDraw;        
[text drawInContext:ctx];

gracias de antemano

nick

¿Fue útil?

Solución

Se debe al espacio de coordenadas volteadas utilizado para CGContexts.Para una explicación completa (con diagramas), consulte aquí .

Editar: Para controlar la posición, traduce su contexto antes de dibujar el texto:

CGContextTranslateCTM(context, x, y);

Editar 2:

Parece que necesita usar un CTFONTREF, no un Uifont.Para un ejemplo, consulte aquí (ver Publicar por Gordon Apple Wed 23 10:40:23 2010).

Editar 3:

A menos que usted necesite específicamente para usar NSATtributedString, recomendaría usar el DrawInrecto de NSString Muchy Simpler: WithFont: LinebreakMode: Alinement: Method.Crea un catextlayer para usted, pero es mucho más sencillo de usar:

    UIFont *font = [UIFont fontWithName:m_font_name size:30.f];
    [m_text drawInRect:text.frame  withFont:font lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];

Editar 4:

Intenta configurar su diccionario como este:

    CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef)fontName, pointSize,NULL);
    CGColorRef color = textColor.CGColor;

    NSDictionary *attributesDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                    (__bridge id)ctFont, (id)kCTFontAttributeName,
                                    color, (id)kCTForegroundColorAttributeName,nil];

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top