2011-05-02 11 views
5

Estoy intentando dibujar una cadena con líneas nuevas (\ n) en una NSView de cacao con alineación central. Por ejemplo, si mi cadena es:Dibujar texto con alineación central en Cocoa View

NSString * str = @"this is a long line \n and \n this is also a long line"; 

me gustaría esto a aparecer algo como:

this is a long line 
     and 
this is also a long line 

Aquí está mi código dentro método NSView drawRect:

NSMutableParagraphStyle * paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; 

[paragraphStyle setAlignment:NSCenterTextAlignment]; 

NSDictionary * attributes = [NSDictionary dictionaryWithObject:paragraphStyle forKey:NSParagraphStyleAttributeName]; 

NSString * mystr = @"this is a long line \n and \n this is also a long line"; 

[mystr drawAtPoint:NSMakePoint(20, 20) withAttributes:attributes]; 

Todavía señala a la texto con alineación izquierda. ¿Qué está mal con este código?

Respuesta

13

La documentación para -[NSString drawAtPoint:withAttributes:] establece lo siguiente:

la anchura (altura para la disposición vertical) de la zona de representación es ilimitado, a diferencia de drawInRect:withAttributes:, que utiliza un rectángulo delimitador. Como resultado, este método representa el texto en una sola línea.

Dado que el ancho es ilimitado, este método descarta la alineación de párrafos y siempre muestra la cadena alineada a la izquierda.

En su lugar, debe usar -[NSString drawInRect:withAttributes:]. Como acepta un marco y un marco tiene un ancho, puede calcular alineaciones centrales. Por ejemplo:

NSMutableParagraphStyle * paragraphStyle = 
    [[[NSParagraphStyle defaultParagraphStyle] mutableCopy] autorelease]; 
[paragraphStyle setAlignment:NSCenterTextAlignment]; 
NSDictionary * attributes = [NSDictionary dictionaryWithObject:paragraphStyle 
    forKey:NSParagraphStyleAttributeName]; 

NSString * mystr = @"this is a long line \n and \n this is also a long line";  
NSRect strFrame = { { 20, 20 }, { 200, 200 } }; 

[mystr drawInRect:strFrame withAttributes:attributes]; 

Tenga en cuenta que usted está goteando paragraphStyle en su código original.

+0

¿Todavía estaría goteando paragraphStyle si estuviera usando Garbage Collection? – AmaltasCoder

+1

@Amal Si está utilizando recolección de basura, no hay fugas. –