在 NSButton 子类中绘制文本

发布于 2024-08-15 07:28:03 字数 34 浏览 2 评论 0原文

如何在 NSButton 子类中添加按钮标题中的文本?

How would I add the text from the title of the button in my NSButton subclass?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝眼泪 2024-08-22 07:28:03

我认为它可能是这样工作的:

- (void) drawRect:(NSRect)aRect {

    // other drawing commands
    // ...
    // other drawing commands

    NSDictionary *att = nil;

    NSMutableParagraphStyle *style =
      [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    [style setLineBreakMode:NSLineBreakByWordWrapping];
    [style setAlignment:NSCenterTextAlignment];
    att = [[NSDictionary alloc] initWithObjectsAndKeys:
                        style, NSParagraphStyleAttributeName, 
                        [NSColor whiteColor],
                        NSForegroundColorAttributeName, nil];
    [style release];

    [self.title drawInRect:self.bounds withAttributes:att];
    [att release];
}

基于 iPhone 上的一些 Objective-C 知识并查看

http://www.cocoadev.com/index.pl?DrawingABoundedString

您可能对网站示例使用静态变量感到满意,也可能不满意。

正如你可能知道的那样,我不是。我的印象是当前图形上下文隐含在调用中。

您可能想根据按钮状态改变文本位置/颜色。

编辑编辑

代码以修复内存泄漏。

Here's how I think it might work:

- (void) drawRect:(NSRect)aRect {

    // other drawing commands
    // ...
    // other drawing commands

    NSDictionary *att = nil;

    NSMutableParagraphStyle *style =
      [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    [style setLineBreakMode:NSLineBreakByWordWrapping];
    [style setAlignment:NSCenterTextAlignment];
    att = [[NSDictionary alloc] initWithObjectsAndKeys:
                        style, NSParagraphStyleAttributeName, 
                        [NSColor whiteColor],
                        NSForegroundColorAttributeName, nil];
    [style release];

    [self.title drawInRect:self.bounds withAttributes:att];
    [att release];
}

based on a bit of Objective-C knowledge on an iPhone and looking at

http://www.cocoadev.com/index.pl?DrawingABoundedString

You may or may not be comfortable with the web site example's use of a static variable.

As you can probably gather I'm not. I get the impression the current graphics context is implicit in the call.

You probably want to vary the text position/color depending on button state.

EDIT

Code edited to fix memory leak.

生寂 2024-08-22 07:28:03

您可以对 NSButtonCell 进行子类化,并重写可用于 NSButtonCellNSCell 的各种 draw 方法中的一个或多个。

You subclass NSButtonCell, and override one or more of the various draw methods available to NSButtonCell and NSCell.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文