gpt4 book ai didi

cocoa - 在 Cocoa View 中绘制居中对齐的文本

转载 作者:行者123 更新时间:2023-12-03 16:10:02 24 4
gpt4 key购买 nike

我试图在 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];

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

最佳答案

-[NSString drawAtPoint:withAttributes:] 的文档说明如下:

The width (height for vertical layout) of the rendering area is unlimited, unlike drawInRect:withAttributes:, which uses a bounding rectangle. As a result, this method renders the text in a single line.

由于宽度不受限制,因此该方法会放弃段落对齐方式并始终将字符串呈现为左对齐。

您应该使用-[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

关于cocoa - 在 Cocoa View 中绘制居中对齐的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5858601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com