objective-c - 在 NSButton 子类中绘制文本

标签 objective-c cocoa drawing subclass

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

最佳答案

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

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

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

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

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

编辑

编辑代码以修复内存泄漏。

关于objective-c - 在 NSButton 子类中绘制文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1930650/

相关文章:

ios - 焦点上的 UITextField 或使用 objective-c 开始编辑输入字段背景颜色更改

macos - 使用反向路径的 CGContextClip()

iOS 如何以编程方式绘制具有不确定半径的 "blue dot",如 iOS7 map 应用程序?

javascript - Canvas 宽度和高度均为 100% 的质量差

iphone - 使用 NSCalendar——获取下个月的第一个星期二

objective-c - RestKit不将数据保存到数据库

ios - 使用名称或任何类型的元数据保存照片

Cocoa:用户通知从未发送

Cocoa:将纹理图集值传递给 NSView

android - 绘图 Canvas FC