macos - NSButtonCell 中的 NSImage 圆角

标签 macos cocoa nsimage nsbuttoncell

我有一个 NSMatrix,其中有几个 NSButton,它们没有文本,只有图像。其中一张图像是从互联网下载的,我希望在我的 OS X 应用程序中将其变成圆角。

我找到了一个几乎就是我正在寻找的答案:How to draw a rounded NSImage但遗憾的是,当我使用它时,它表现得很疯狂:

// In my NSButtonCell subclass
- (void)drawImage:(NSImage*)image withFrame:(NSRect)imageFrame inView:(NSView*)controlView
{
    // [super drawImage:image withFrame:imageFrame inView:controlView];

    [NSGraphicsContext saveGraphicsState];

    NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:imageFrame xRadius:5 yRadius:5];
    [path addClip];

    [image drawInRect:imageFrame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];

    [NSGraphicsContext restoreGraphicsState];
}

问题是,如果图像是部分透明的 (PNG),那么它会被完全破坏,我只能在黑色背景上看到几个白色像素。

如果图像不透明,那么它会获得圆角,但会旋转 180°,我不知道为什么。

有什么建议吗?

最佳答案

在绘制图像之前,您需要确保正确设置图像的大小,并且应该使用 NSImage 方法 drawInRect:fromRect:operation:fraction:respectFlipped:hints: 确保图像以正确的方式向上绘制:

- (void)drawImage:(NSImage*)image withFrame:(NSRect)imageFrame inView:(NSView*)controlView
{
    // [super drawImage:image withFrame:imageFrame inView:controlView];

    [NSGraphicsContext saveGraphicsState];

    NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:imageFrame xRadius:5 yRadius:5];
    [path addClip];

    //set the size
    [image setSize:imageFrame.size];

    //draw the image
    [image drawInRect:imageFrame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0 respectFlipped:YES hints:nil];

    [NSGraphicsContext restoreGraphicsState];
}

如果执行此操作,即使是半透明的 PNG 图像,图像也应该正确绘制。

关于macos - NSButtonCell 中的 NSImage 圆角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8332963/

相关文章:

objective-c - 为什么我无法加载 Assets 目录中的图像?

swift - 如何在 Swift 中将 NSImage 写入 JPEG 文件?

macos - docker为什么将带有数值的文件挂载为目录?

c - 如何在 Mac OS X 上通过 C API 获取当前线程的堆栈大小? (不含 cocoa 或碳)

Mac 上的 Java App 每次都要求允许网络连接

cocoa - *在*编辑期间替换 NSTextFieldCell 的内容?

json - 如何在新的 Mono 类库上使用 JSON.Net?

cocoa - Cocoa 语音问题简介

xml - Cocoa XML 阅读器应用程序

objective-c - 如何从组合 TIFF 中获取合适的 CGImage 用于显示比例