在Cocoa View中绘制具有中心对齐的文本

时间:2011-05-02 14:48:00

标签: cocoa macos nsview

我正在尝试在具有中心对齐的cocoa 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];

它仍然以左对齐方式绘制文本。这段代码有什么问题?

1 个答案:

答案 0 :(得分: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