【问题标题】:Drawing text in a NSButton subclass - positioning在 NSButton 子类中绘制文本 - 定位
【发布时间】:2009-12-21 13:15:19
【问题描述】:

我有一个自定义按钮: My Button http://cld.ly/29ubq

我需要文本居中,这是我的代码:

NSMutableParagraphStyle *style =
    [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setLineBreakMode:NSLineBreakByWordWrapping];
[style setAlignment:NSLeftTextAlignment];
att = [[NSDictionary alloc] initWithObjectsAndKeys:
           style, NSParagraphStyleAttributeName, 
           [NSColor blackColor],
           NSForegroundColorAttributeName, nil];
[style release];
// other Drawing code here
[[self title] drawInRect:[self bounds] withAttributes:att];

如何将文本置于按钮中心(而不是边界中心)?

【问题讨论】:

    标签: objective-c cocoa drawing custom-controls


    【解决方案1】:

    您想首先使用NSString -sizeWithAttributes: 获取标题的大小。然后您可以使用该尺寸在您的范围内调整标题的绘制。

    这有一个技巧,因为在此过程中的某个时刻,您几乎总是会被除以二。当你这样做时,你可能会得到一个半像素的结果,Cocoa 会很乐意使用它。但是,它会导致您的文字模糊。你几乎总是想在你的坐标上调用floor(),然后再绘制它们以使自己回到整数像素。

    编辑:一个居中的基本示例(这应该可以正确编译,我还没有编译它,我最近的工作已经在颠倒的 iPhone 上结束了):

    NSRect rect;
    rect.size = [[self title] sizeWithAttributes:att];
    rect.origin.x = floor( NSMidX([self bounds]) - rect.size.width / 2 );
    rect.origin.y = floor( NSMidY([self bounds]) - rect.size.height / 2 );
    [[self title] drawInRect:rect withAttributes:att];
    

    不管怎样,都是这样的。由于按钮的绘制方式,您可能需要稍微偏移,但这是基本思想。

    【讨论】:

      【解决方案2】:

      您可能对Setting a Button’s Image 感兴趣,它还解释了如何相对于按钮的图像定位标题。

      【讨论】:

      • 我想尝试没有图像...我想填充按钮
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多