开发者

Problem with NSColors in cocoa

i am trying to compose colors using NSColor and when i am trying to create RGB color with the following values it just displays the white colors instead:

(r,g,b):(50,50,50)
(r,g,b):(100,100,100)
(r,g,b):(150,150,150)
(r,g,b):(200,200,200)

etc...

the code used to create the colors is:

// the code to genearet simple images with background colors

NSColor * myColor = [NSColor colorWithDeviceRed:100.0 green:100.0 blue:100.0 alpha:1.0];
NSImage* image1 开发者_开发百科= [[NSImage alloc] initWithSize:NSMakeSize(10.0,  100.0)];
NSRect imageBounds1 = NSMakeRect (0, 0, 10, 100);

[image1 lockFocus];
[myColor set];
NSRectFill (imageBounds1);
[image1 unlockFocus];

I couldn't find any resource or sample on the web, which provides some sort of help on my above queries.It's highly appreciated if someone could share his wisdom on how I can achieve this.

Thanks in advance..


If I recall correctly you'll want the range 0-1 as your RGB as well


NSColor components have values in [0..1] so you should normalize the values you have, e.g.:

NSColor * myColor = [NSColor colorWithDeviceRed:100.0/255 green:100.0/255 blue:100.0/255 alpha:1.0];

If you try to set values greater then 1 to colour components then they're interpreted as 1, so your code will be actually equivalent to

NSColor * myColor = [NSColor colorWithDeviceRed:1.0 green:1.0 blue:1.0 alpha:1.0];

Which creates white colour.


As stated in the documentation:

Values below 0.0 are interpreted as 0.0, and values above 1.0 are interpreted as 1.0

This means that your values (100,100,100) are going to be converted in (1.0,1.0,1.0) which is white. What you have to do is convert each channel value using the following equation:

100 : 255 = x : 1.0 => x = 100/255

where x is the value that you will use for the method

-(NSColor*)colorWithDeviceRed:CGFloat red green:CGFloat green blue:CGFloat blue alpha:CGFloat alpha];

You should have something like this in your code

[NSColor colorWithDeviceRed:100.0/255.0 green:100.0/255.0 blue:100.0/255.0 alpha:1.0];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜