我正在寻找更改NSView
的backgroundColor
的最佳方法。我还希望能够为NSView
设置适当的alpha
掩码。类似于:
myView.backgroundColor = [NSColor colorWithCalibratedRed:0.227f
green:0.251f
blue:0.337
alpha:0.8];
我注意到NSWindow
有这个方法,我不太喜欢NSColorWheel
或NSImage
背景选项,但如果它们是最好的,我愿意使用它们。
发布于 2010-06-03 09:55:42
是啊,你自己的答案是对的。您还可以使用Cocoa方法:
- (void)drawRect:(NSRect)dirtyRect {
// set any NSColor for filling, say white:
[[NSColor whiteColor] setFill];
NSRectFill(dirtyRect);
[super drawRect:dirtyRect];
}
在Swift中:
class MyView: NSView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// #1d161d
NSColor(red: 0x1d/255, green: 0x16/255, blue: 0x1d/255, alpha: 1).setFill()
dirtyRect.fill()
}
}
发布于 2011-10-03 20:49:59
一个简单有效的解决方案是将视图配置为使用核心动画层作为其后备存储。然后,您可以使用-[CALayer setBackgroundColor:]
设置图层的背景颜色。
- (void)awakeFromNib {
self.wantsLayer = YES; // NSView will create a CALayer automatically
}
- (BOOL)wantsUpdateLayer {
return YES; // Tells NSView to call `updateLayer` instead of `drawRect:`
}
- (void)updateLayer {
self.layer.backgroundColor = [NSColor colorWithCalibratedRed:0.227f
green:0.251f
blue:0.337
alpha:0.8].CGColor;
}
就这样!
发布于 2015-01-15 08:10:25
如果首先setWantsLayer设置为YES,则可以直接操纵层背景。
[self.view setWantsLayer:YES];
[self.view.layer setBackgroundColor:[[NSColor whiteColor] CGColor]];
https://stackoverflow.com/questions/2962790
复制相似问题