为了账号安全,请及时绑定邮箱和手机立即绑定

更改NSView背景颜色的最佳方法

更改NSView背景颜色的最佳方法

动漫人物 2019-11-25 09:54:58
我在寻找改变的最佳途径backgroundColor的NSView。我还希望能够为设置适当的alpha蒙版NSView。就像是:myView.backgroundColor = [NSColor colorWithCalibratedRed:0.227f                                                    green:0.251f                                                     blue:0.337                                                    alpha:0.8];我注意到NSWindow有这种方法,我也不喜欢NSColorWheel或NSImage背景选项,但是如果它们是最好的,那就愿意使用。
查看完整描述

3 回答

?
侃侃尔雅

TA贡献1801条经验 获得超15个赞

是的,您自己的答案是正确的。您还可以使用可可方法:


- (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()

    }


}


查看完整回答
反对 回复 2019-11-25
?
哈士奇WWW

TA贡献1799条经验 获得超6个赞

一个简单,有效的解决方案是将视图配置为使用Core Animation层作为其后备存储。然后,您可以-[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;

}


查看完整回答
反对 回复 2019-11-25
?
呼唤远方

TA贡献1856条经验 获得超11个赞

想想我想出了怎么做:


- (void)drawRect:(NSRect)dirtyRect {

    // Fill in background Color

    CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];

    CGContextSetRGBFillColor(context, 0.227,0.251,0.337,0.8);

    CGContextFillRect(context, NSRectToCGRect(dirtyRect));

}


查看完整回答
反对 回复 2019-11-25
  • 3 回答
  • 0 关注
  • 1111 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信