2011-05-02 18 views
5

我想繪製一個帶有中心對齊的可可NSView的新行(\ n)的字符串。例如,如果我的字符串是:在可可視圖中繪製帶有中心對齊的文本

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

我想這在一定程度上表現爲:

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

這裏是我的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]; 

它仍然吸引了與左對齊的文本。這段代碼有什麼問題?

回答

13

-[NSString drawAtPoint:withAttributes:]狀態以下文檔:渲染區域的

的寬度(高度爲垂直佈局)是無限的,不像drawInRect:withAttributes:,它使用一個邊界矩形。因此,此方法將文本渲染爲單行。

由於寬度無限制,該方法丟棄段落對齊並始終呈現字符串左對齊。

您應該使用-[NSString drawInRect:withAttributes:]來代替。由於它接受一個框架並且框架具有寬度,所以它可以計算中心對齊。例如:

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]; 

注意,你是在爲你的原始代碼泄漏paragraphStyle

+0

如果我正在使用垃圾回收功能,我還會泄漏paragraphStyle嗎? – AmaltasCoder 2011-05-03 05:58:14

+1

@Amal如果你正在使用垃圾收集,那就沒有泄漏。 – 2011-05-03 05:59:00