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

Ama*_*der 5 macos cocoa nsview

我试图在具有中心对齐的可可NSView中绘制带有新行(\n)的字符串.例如,如果我的字符串是:

NSString * str = @"this is a long line \n and \n this is also a long line"; 
Run Code Online (Sandbox Code Playgroud)

我希望这看起来像:

  this is a long line
         and
this is also a long line
Run Code Online (Sandbox Code Playgroud)

这是我在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];
Run Code Online (Sandbox Code Playgroud)

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

小智 14

-[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];
Run Code Online (Sandbox Code Playgroud)

请注意,您paragraphStyle的原始代码泄漏了.