我想在NSViewController
中实现深色/浅色模式下图片颜色的切换。
我使用以下代码来改变图片的颜色:
- (NSImage *)image:(NSImage *)image withColour:(NSColor *)colour
{
NSImage *img = image.copy;
[img lockFocus];
[colour set];
NSRect imageRect = NSMakeRect(0, 0, img.size.width, img.size.height);
NSRectFillUsingOperation(imageRect, NSCompositingOperationSourceAtop);
[img unlockFocus];
return img;
}
我已尝试从
viewWillLayout
调用此方法。self.help1Image.image = [self image:self.help1Image.image withColour:[NSColor systemRedColor]];
但是似乎系统颜色总是返回相同的RGB值。
我还尝试侦听通知AppleInterfaceThemeChangedNotification
,但即使在此处,RGB值也保持不变1.000000 0.231373 0.188235
。
[[NSDistributedNotificationCenter defaultCenter] addObserverForName:@"AppleInterfaceThemeChangedNotification"
object:nil
queue:nil
usingBlock:^(NSNotification * _Nonnull note) {
NSLog(@"AppleInterfaceThemeChangedNotification");
self.help1Image.image = [self image:self.help1Image.image withColour:[NSColor systemRedColor]];
NSColorSpace *colorSpace = [NSColorSpace sRGBColorSpace];
NSColor *testColor = [[NSColor systemBlueColor] colorUsingColorSpace:colorSpace];
CGFloat red = [testColor redComponent];
CGFloat green = [testColor greenComponent];
CGFloat blue = [testColor blueComponent];
NSLog(@"%f %f %f", red, green, blue);
}];
我已经在一个NSButtonCell
子类中通过覆盖layout
方法,成功实现了功能,但在NSViewController
中无法做到。
[NSAppearance setCurrentAppearance:self.view.effectiveAppearance];
我可以在我提问中发布的通知中设置它,之后颜色就正确了。 - Darren