简体   繁体   中英

NSMenuItem image color becomes dark when selected

I am using NSPopUpButton with title and image. Below is my code:

[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

Color of image becomes dark if I select popup button:

在此处输入图片说明

Have you tried to use NSRectFill to draw the color to the image? As far as I know, drawSwatchInRect does some alpha compositing.

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM