Search code examples
objective-crgbbrightnesshsb

how to calculate Brightness of RGB color?


i've got my function:

-(void)rgbToHSBWithR:(float)red G:(float)green B:(float)blue {

float brightness = red * 0.3 + green * 0.59 + blue * 0.11; // found in stackoverflow
NSLog(@"%f",brightness);
}

and it isn't work for me.

for example: r:84 g:67 b:73. function return 72.760002. In Photoshop brightness for this color is 33%. What's wrong?

Thanks.


Solution

  • Use UIColor or NSColor:

    -(void)rgbToHSBWithR:(float)red G:(float)green B:(float)blue {
        // assuming values are in 0 - 1 range, if they are byte representations, divide them by 255
        UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:1];
    
        float h, s, b;
        if ([color getHue:&h saturation:&s brightness:&b alpha:NULL])
        {
            // h, s, & b now contain what you need
        }
    }