iphone objective-c ios7 core-text

iphone - CGContextSelectFont equivalente



objective-c ios7 (3)

En iOS7 CGContextSelectFont está en desuso. El mensaje de desaprobación dice que tengo que usar Core Text, pero no sé cuál es el equivalente exacto de este fragmento de código:

CGContextSelectFont(context, "Helvetica", kBarLabelSize, kCGEncodingMacRoman); CGContextSetTextDrawingMode(context, kCGTextFill); CGContextSetRGBFillColor(context, 0, 0, 0, 1.0); CGContextSetTextMatrix (context, CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0)); CGContextShowTextAtPoint(context, barX, barY, [@"Some text" cStringUsingEncoding:NSUTF8StringEncoding], [barValue length]);

He podido crear la fuente con este código:

CFMutableAttributedStringRef attrStr = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0); CTFontRef font = CTFontCreateWithName(CFSTR("Helvetica"), kBarLabelSize, NULL); CFAttributedStringSetAttribute(attrStr, CFRangeMake(0, CFAttributedStringGetLength(attrStr)), kCTFontAttributeName, font);

Pero ahora, ¿puedo "dibujar" un texto con esta fuente en el contexto?


He encontrado, al menos en mi caso, que el problema con la nueva interfaz NSString.drawAtPoint es que puede volverse del revés, dependiendo de cómo esté usando el contexto.

Una alternativa es utilizar los métodos de Core Text, específicamente la interfaz CTLine por lo tanto:

NSDictionary *attribs = @{NSFontAttributeName:[UIFont fontWithName:@"Helvetica" size:14.0]}; NSAttributedString *fontStr = [[NSAttributedString alloc] initWithString:@"some text" attributes:attribs]; CTLineRef displayLine = CTLineCreateWithAttributedString( (__bridge CFAttributedStringRef)fontStr ); CGContextSetTextPosition( ctx, xPosition, yPosition ); CTLineDraw( displayLine, ctx ); CFRelease( displayLine );


Lo mejor que puedo entender de su código, el equivalente exacto es:

CGContextSetTextDrawingMode(context, kCGTextFill); // This is the default [[UIColor blackColor] setFill]; // This is the default [@"Some text" drawAtPoint:CGPointMake(barX, barY) withAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Helvetica" size:kBarLabelSize] }];

Tenga en cuenta que sus llamadas a CGContextSetTextDrawingMode y CGContextSetRGBFillColor están configurando los valores a los valores predeterminados. Su llamada a CGContextSetTextMatrix no es necesaria cuando se utiliza el dibujo de UIKit de esta manera.

Sin embargo, no tengo idea de qué [barValue length] está aquí. Supongo que simplemente lo utilizó incorrectamente para la longitud de @"Some text" . (la length no es el número de bytes que es lo que necesita. Lo que probablemente quiso decir fue [barValue lengthOfBytesUsingEncoding:NSUTF8StringEncoding] ).

Tenga en cuenta que el dibujo de la cadena UIKit (que se ve aquí) envuelve el Texto Central.


Probablemente puedes usar lo siguiente para reemplazarlo.

  1. CGContextSetFont
  2. CGContextSetFontSize