【问题标题】:I get wrong custom background color and black color instead of background image in NSView我在 NSView 中得到错误的自定义背景颜色和黑色而不是背景图像
【发布时间】:2015-02-22 02:21:29
【问题描述】:

我正在尝试制作一个简单的应用程序,其中我有一个侧边栏,并且我正在尝试根据 PSD 文件中的 RGB 值获取背景颜色,或者使用背景图像作为图案......

我在这两种方式上都进行了尝试,但到目前为止没有任何效果。任何帮助将不胜感激。

-(void) drawRect:(NSRect)dirtyRect {
    CALayer *viewLayer = [CALayer layer];
    [viewLayer setBackgroundColor:CGColorCreateGenericRGB(85.0, 179.0, 217.0, 1.0)]; //RGB plus Alpha Channel
    [self setWantsLayer:YES]; // view's backing store is using a Core Animation Layer
    [self setLayer:viewLayer];
}

这段代码应该是蓝色的,结果几乎是白色的......甚至不接近我想要的。

第二个代码,显示黑色背景,即使我的png文件在支持文件的文件夹中。

- (void)drawRect:(NSRect)dirtyRect {
    NSGraphicsContext* theContext = [NSGraphicsContext currentContext];
    [theContext saveGraphicsState];
    [[NSGraphicsContext currentContext] setPatternPhase:NSMakePoint(0,[self frame].size.height)];
    [self.customBackgroundColour set];
    NSRectFill([self bounds]);
    [theContext restoreGraphicsState];
}

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.customBackgroundColour = [NSColor colorWithPatternImage:          
        [NSImage imageNamed:@"buttonBg.png"]];
    }
return self;
}

再次感谢任何帮助。

【问题讨论】:

  • 您确定您的-initWithFrame: 正在被调用吗?此外,您通常不应更改 -drawRect: 中的视图状态(例如 wantsLayerlayer 属性)。是用来画画的。状态应在此之前建立;最迟在-viewWillDraw

标签: objective-c macos cocoa


【解决方案1】:

如果我没记错的话,CGColorCreateGenericRGB 的预期范围是 0.0-1.0,并会解释为什么它是白色的。这应该可以解决白色问题。

[viewLayer setBackgroundColor:CGColorCreateGenericRGB(85.0/255.0, 179.0/255.0, 217.0/255.0, 1.0)]; //RGB plus Alpha Channel

希望对您有所帮助。

【讨论】:

  • 这段代码有效,而且颜色与我想要的颜色更相似,但奇怪的是,RGB 值发生了变化(我制作了 printscreen,我使用了颜色选择器 photoshop 工具),现在 RGB 值是 109,192,223....你知道为什么会这样吗?
  • 对此没有一个好的答案。可能是模拟器或屏幕。不确定颜色选择器如何确定颜色:/
  • 还是谢谢...我会继续寻找一种使用背景图片的方法,因为我似乎不能太依赖颜色解决方案。
最近更新 更多