NSMenuitem 模板图像色调颜色不变

NSMenuitem tempelate image tint color not changing

我有自定义视图,它有图像视图图像,我正在设置 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;
}

非常感谢任何帮助..

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

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

[tinted setTemplate:NO];

HTH

你真的应该避免使用 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;
    }];
}