【问题标题】:Draw text with center alignment in Cocoa View在 Cocoa View 中绘制居中对齐的文本
【发布时间】:2011-05-02 14:48:00
【问题描述】:

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

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

【问题讨论】:

    标签: cocoa macos nsview


    【解决方案1】:

    -[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

    【讨论】:

    • 如果我使用垃圾收集器,我还会泄漏段落样式吗?
    • @Amal 如果你使用垃圾回收,没有泄漏。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 2015-07-29
    • 1970-01-01
    • 2016-06-25
    相关资源
    最近更新 更多