我有一个nsmatrix,其中有几个nsbutton,没有文字,只有图像。其中一张图像是从互联网下载的,我想在OS X应用程序中将其圆润。

我找到了一个答案,几乎是我想要的: 如何绘制圆形的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图像,图像也应正确绘制。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top