NSMenuitem模板图像色调颜色不变

时间:2019-04-17 06:04:42

标签: objective-c macos cocoa

我有具有图像视图图像的customview,我正在将NSImageNameMenuOnStateTemplate设置为具有颜色的图像视图,但是没有应用颜色

NSImage *tintImage = [self tintedImage:[NSImage imageNamed:NSImageNameMenuOnStateTemplate] withTintColor:NSColor.whiteColor];

myimageView.image = tintImage
-(NSImage*)tintedImage:(NSImage*)image withTintColor:(NSColor*)color{
    NSImage *tinted = [image copy];
    [tinted lockFocus];
    [color set];

    NSRect imageRect = {NSZeroPoint, [image size]};
    NSRectFillUsingOperation(imageRect, NSCompositingOperationSourceAtop);
    [image unlockFocus];
    return tinted;
}

最感谢您的帮助。.

2 个答案:

答案 0 :(得分:0)

[image unlockFocus];更改为[tinted unlockFocus];

对于macOS,您需要将setTemplate设置为NO

[tinted setTemplate:NO];

HTH

答案 1 :(得分:0)

您确实应该避免使用lockFocus / unlockFocus。它们已过时,您已通过锁定一个图像并解锁另一个图像来滥用它们。使用`+ [NSImage imageWithSize:flipped:drawingHandler:]

作为NSImage的类别补充:

- (NSImage *)imageWithSolidFillColor:(NSColor *)color
{
    return [NSImage imageWithSize:self.size flipped:false drawingHandler:^BOOL(NSRect dstRect) {
        [self drawInRect:dstRect fromRect:NSZeroRect operation:NSCompositingOperationSourceOver fraction:1.0];
        [color set];
        NSRectFillUsingOperation(dstRect, NSCompositeSourceAtop);
        return YES;
    }];
}