Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSColor | Creating Color from RGB Values

In my application, i will get RGB Values as a unsigned character so it will not be more then 255, I am using NSColor API to create the color and will make use of it to draw the font and background color,

this is the function that i have written

+(NSColor *)getColorFromRGB:(unsigned char)r blue:(unsigned char)b green:(unsigned char)g
{
    CGFloat rFloat = r/255.0;
    CGFloat gFloat = g/255.0;
    CGFloat bFloat = b/255.0;

    //  return [NSColor colorWithCalibratedRed:((float)r/255.0) green:((float)g/255.0) blue:((float)b/255.0) alpha:1.0];
    return [NSColor colorWithCalibratedRed:rFloat green:gFloat blue:bFloat alpha:1.0];
}

In almost all case, when i compare the Color using my RGB Value in RGB palate, color is not matching, For example, when i pass ,

r = 187, g = 170, b = 170,

It should draw the light gray, but i am getting complete whilte color, in this case,

anyone has an idea, what i am doing wrong,

Kind Regards

Rohan

like image 947
Amitg2k12 Avatar asked Feb 23 '11 12:02

Amitg2k12


People also ask

Why does RGB only go to 255?

Each channel (Red, Green, and Blue are each channels) is 8 bits, so they are each limited to 256, in this case 255 since 0 is included.

How do you convert RGB to integer?

So far I use the following to get the RGB values from it: // rgbs is an array of integers, every single integer represents the // RGB values combined in some way int r = (int) ((Math. pow(256,3) + rgbs[k]) / 65536); int g = (int) (((Math. pow(256,3) + rgbs[k]) / 256 ) % 256 ); int b = (int) ((Math.

How do you use RGB in color?

The main use of the RGB color model is for displaying images on electronic devices. In this process of the RGB color model, if the three colors are superimposed with the least intensity, then the black color is formed, and if it is added with the full intensity of light, then the white color is formed.


2 Answers

The code works for me. Try debugging, did you remember to call -set on your color after creating it? Here is some example code that works:

static NSColor *colorFromRGB(unsigned char r, unsigned char g, unsigned char b)
{
    return [NSColor colorWithCalibratedRed:(r/255.0f) green:(g/255.0f) blue:(b/255.0f) alpha:1.0];
}

...

- (void)drawRect:(NSRect)rect {
    NSColor *c = colorFromRGB(50, 100, 255);
    [c set]; // <-- Important
    NSRectFill(rect);
}
like image 200
Dietrich Epp Avatar answered Sep 21 '22 19:09

Dietrich Epp


If you are passing the input components out of 255 and you want to restrict it within 255 for safety purpose, you can try this:

CGFloat rFloat = r % 255.0; CGFloat gFloat = g % 255.0; CGFloat bFloat = b % 255.0;

Instead of divide use % value.

like image 32
spd Avatar answered Sep 22 '22 19:09

spd