gpt4 book ai didi

macos - NSButtonCell 中的 NSImage 圆角

转载 作者:行者123 更新时间:2023-12-03 16:58:58 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com