2010-03-30 6 views
36

He buscado cargas y no he podido encontrar una respuesta.¿Cómo cambiar el espacio entre letras de UILabel/UIFont?

Tengo un UILabel normal, definido de esta manera:

UILabel *totalColors = [[[UILabel alloc] initWithFrame:CGRectMake(5, 7, 120, 69)] autorelease]; 
    totalColors.text = [NSString stringWithFormat:@"%d", total]; 
    totalColors.font = [UIFont fontWithName:@"Arial-BoldMT" size:60]; 
    totalColors.textColor = [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:1.0]; 
    totalColors.backgroundColor = [UIColor clearColor]; 
    [self addSubview:totalColors]; 

y quería el espacio horizontal entre las letras, a ser más estrictos, mientras que manteniendo el tamaño de fuente.

¿Hay alguna manera de hacerlo? Debería ser algo bastante básico de hacer.

Saludos muchachos, Andre

ACTUALIZACIÓN:

así que estaba obligado a hacerlo de esta manera:

- (void) drawRect:(CGRect)rect 
{ 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    CGContextSelectFont (context, "Arial-BoldMT", 60, kCGEncodingMacRoman); 
    CGContextSetCharacterSpacing (context, -10); 
    CGContextSetTextDrawingMode (context, kCGTextFill); 

    CGContextSetRGBFillColor(context, 221/255.0, 221/255.0, 221/255.0, 221/255.0); 
    CGAffineTransform xform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0); 
    CGContextSetTextMatrix(context, xform); 

    char* result = malloc(17); 
    sprintf(result, "%d", totalNumber); 

    CGContextShowTextAtPoint (context, 0, 54, result, strlen(result)); 
} 

Pero necesitan alinear esta a la derecha. Podría hacerlo manualmente si supiera el ancho del texto dibujado, pero resulta casi imposible encontrarlo.

He leído sobre ATSU, pero no he podido encontrar ningún ejemplo.

Esto es una mierda:/

+0

posible duplicado de http://stackoverflow.com/questions/1063268/is-it -posible-para-alterar-la-letra-espaciado-kerning-de-una-fuente-con-cocoa-touch –

+0

así que no hay otra manera de hacerlo sin usar fuentes personalizadas o sin usar Quartz 2D? – Andre

+1

Puede obtener el tamaño de la región que ocupará el texto en un UILabel invocando - (CGSize) sizeWithFont: (UIFont *) fuente minFontSize: (CGFloat) minFontSize actualFontSize: (CGFloat *) actualFontSize forWidth: (CGFloat) width lineBreakMode :(UILineBreakMode) método lineBreakMode de la categoría NSString UIStringDrawing. Entonces, puedes disminuir ese tamaño por cuanto encogiste tu texto, supongo. Si aún lo necesita :) –

Respuesta

8

He encontrado una solución para el espaciado entre letras y la alineación a la derecha.

aquí va:

NSString *number = [NSString stringWithFormat:@"%d", total]; 

    int lastPos = 85; 

    NSUInteger i; 
    for (i = number.length; i > 0; i--) 
    { 
     NSRange range = {i-1,1}; 
     NSString *n = [number substringWithRange:range]; 

     UILabel *digit = [[[UILabel alloc] initWithFrame:CGRectMake(5, 10, 35, 50)] autorelease]; 
     digit.text = n; 
     digit.font = [UIFont fontWithName:@"Arial-BoldMT" size:60]; 
     digit.textColor = [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:1.0]; 
     digit.backgroundColor = [UIColor clearColor]; 
     [self addSubview:digit]; 

     CGSize textSize = [[digit text] sizeWithFont:[digit font]]; 
     CGFloat textWidth = textSize.width; 

     CGRect rect = digit.frame; 
     rect.origin.x = lastPos - textWidth; 
     digit.frame = rect; 

     lastPos = rect.origin.x + 10; 
    } 

El espacio entre las letras es el "10" en la última línea. La alineación proviene de los últimosPos.

Espero que esto ayude a cualquiera por ahí.

+3

Su método es plausible (y el primero que se me ocurrió) pero desafortunadamente podría no funcionar bien si necesita renderizar muchas regiones de texto. Creo que la actualización proporcionada por Andre es mucho mejor en el caso general –

0

No en cualquier versión disponible públicamente de iPhone OS. ;-) Si usted es un desarrollador de iPhone actual, puede hacerse una idea de dónde va el sistema operativo de iPhone mirando las notas "Novedades" para iPhone OS 3.2.

Actualización: iOS v3.2, que agregó soporte para kerning, todavía estaba bajo NDA cuando publiqué esto. Para una respuesta de actualización hasta la fecha, vea How to set kerning in iPhone UILabel.

+0

Por favor revisa mi actualización. ¿Algunas ideas? – Andre

+0

Puede determinar la dimensión del texto dibujado en UILabel utilizando textRectForBounds: limitedToNumberOfLines :. ¡Parece que encontraste lo que estabas buscando! Acabo de asumir que estabas buscando kerning. Feliz codificación! – Zack

+0

A partir de esta fecha, la versión actual de iOS es 6.1. La forma de lograr esto (fácilmente) es mediante el uso de 'NSAttributedString', pero no estaba disponible en la mayoría de los controles hasta iOS 6.0 – DBD

11

He extendido UILabel para cambiar el espaciado entre caracteres. Esto debería resolver la caja y extraer la fuente, el texto, el color, etc. de la propia UILabel (¡la codificación adecuada!).

Puede notar que dibujo el texto dos veces, primero con color claro. Esto es para centrar automáticamente el texto en la etiqueta. Si bien esto puede ser ineficiente, ¿no es bueno ser centrado automáticamente?

¡Disfrútalo!

@interface RALabel : UILabel { 
} 
@end 

@implementation RALabel 

- (void) drawRect:(CGRect)rect 
{ 

    // Drawing code 

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSelectFont (context, [self.font.fontName cStringUsingEncoding:NSASCIIStringEncoding], self.font.pointSize, kCGEncodingMacRoman); 
    CGContextSetCharacterSpacing(context, 1); 
    CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]); 
    CGAffineTransform myTextTransform = CGAffineTransformScale(CGAffineTransformIdentity, 1.f, -1.f); 
    CGContextSetTextMatrix (context, myTextTransform); 

    // draw 1 but invisbly to get the string length. 
    CGPoint p =CGContextGetTextPosition(context); 
    float centeredY = (self.font.pointSize + (self.frame.size.height- self.font.pointSize)/2)-2; 
    CGContextShowTextAtPoint(context, 0, centeredY, [self.text cStringUsingEncoding:NSASCIIStringEncoding], [self.text length]); 
    CGPoint v =CGContextGetTextPosition(context); 

    // calculate width and draw second one. 
    float width = v.x - p.x; 
    float centeredX =(self.frame.size.width- width)/2; 
    CGContextSetFillColorWithColor(context, [self.textColor CGColor]); 
    CGContextShowTextAtPoint(context, centeredX, centeredY, [self.text cStringUsingEncoding:NSASCIIStringEncoding], [self.text length]); 

} 
+1

solo se pueden usar caracteres ascii con esta solución – Bastian

40

Desde iOS 6 puede usar NSAttributedString en UILabel.

En una cadena con atributos que puede utilizar para establecer atribuir NSKernAttributeName letra espaciado

NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc] initWithString: @"Test test test test "]; 
[attrStr addAttribute:NSKernAttributeName value:@(4.0) range:NSMakeRange(0, attrStr.length)]; 

UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0, 300, 300, 100)]; 
label.attributedText = attrStr; 
+1

thanx para ahorrar mi tiempo :) (y) – ishhhh

3

En Swift:

let myTitle = "my title" 
let titleLabel = UILabel() 
let attributes: NSDictionary = [ 
    NSFontAttributeName:UIFont(name: "HelveticaNeue-Light", size: 20), 
    NSForegroundColorAttributeName:UIColor.whiteColor(), 
    NSKernAttributeName:CGFloat(2.0) 
] 
let attributedTitle = NSAttributedString(string: myTitle, attributes: attributes as? [String : AnyObject]) 

titleLabel.attributedText = attributedTitle 
titleLabel.sizeToFit() 
Cuestiones relacionadas