选择时NSMenuItem图像颜色变暗

时间:2016-04-21 12:10:10

标签: objective-c macos cocoa nsmenuitem nspopupbutton

我正在使用带标题和图片的NSPopUpButton。以下是我的代码:

[self.popup addItemWithTitle:@"Parag"];
[[self.popup lastItem] setImage:[NSImage swatchWithColor:[NSColor greenColor] size:NSMakeSize(10.0, 10.0)]];

Creating NSImage from NSColor

@interface NSImage (ImageAdditions)

+(NSImage *)swatchWithColor:(NSColor *)color size:(NSSize)size;


@end

@implementation NSImage (ImageAdditions)

+(NSImage *)swatchWithColor:(NSColor *)color size:(NSSize)size
{
    NSImage *image = [[NSImage alloc] initWithSize:size];
    [image lockFocus];
    [color drawSwatchInRect:NSMakeRect(0, 0, size.width, size.height)];
    [image unlockFocus];
    return image;
}

@end

如果选择弹出按钮,图像颜色会变暗:

enter image description here

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用NSRectFill为图像绘制颜色?据我所知,drawSwatchInRect做了一些alpha合成。

@implementation NSImage (ImageAdditions)

+(NSImage *)swatchWithColor:(NSColor *)color size:(NSSize)size
{
    NSImage *image = [[NSImage alloc] initWithSize:size];
    [image lockFocus];
    [color set];
    NSRectFill(NSMakeRect(0, 0, size.width, size.height));
    [image unlockFocus];
    return image;
}

@end