Objective-C RGB for HSB

Say I have the color FF0000, red. Finding a darker color is easy, I just type CC instead of FF, but let me say that I have an AE83FC color, which is a complex color, how the hell can find a lighter or darker version of this automatically?

I realized that an easy way to do this is to convert RGB to HSB [Hue, Saturation, Brightness]

How do I do this in Objective-C?

Let's say I have RGB, which is: 1.0, 0.0, 0.0. This is red.

CGFloat r = 1.0; CGFloat g = 0.0; CGfloat b = 0.0; 

How do I convert this to HSB and then convert colors and return it to RGB so that I can use CGContextRGBSetFillColor?

Are there any HSB features?

Please, help.:)

+1
objective-c colors iphone rgb
source share
2 answers

First, remember that three numbers do not describe color, three numbers along with color space. RGB is not a color space, it is what is called a color model. There are many color spaces with the RGB model. So ((1,0,0), sRGB) is different from color ((1,0,0), Adobe RGB). Do you know how string encodings work, where a bunch of bytes is not a string in itself? It is very similar. It also looks like you're asking for problems when you want to look at the values ​​of the components, because this is an opportunity to ruin the color space processing.

Sorry, I can not help myself. Anyway, I will answer the question as if your original color was ((1,0,0), Generic RGB).

 NSColor *color = [NSColor colorWithCalibratedRed:1 green:0 blue:0 alpha:1]; NSLog(@"hue! %g saturation! %g brightness! %g, [color hueComponent], [color saturationComponent], [color brightnessComponent]); 

and on the other hand

 NSColor *color = [NSColor colorWithCalibratedHue:h saturation:s brightness:b alpha:1]; NSLog(@"red! %g green! %g blue! %g, [color redComponent], [color greenComponent], [color blueComponent]); 

These fooComponent methods do not work with all colors, but only in two specific color spaces, see docs. You already know that you are good if you yourself created the colors using the methods above. If you have a color of unknown origin, you can (try) convert it to a color space in which you can use these component methods with the help of -[NSColor colorUsingColorspaceName:] .

+4
source share

There’s no need to go all the way to the HSB. If you want to find a darker version of the color, simply multiply each component of R, G and B with a number from 0 to 1, and you will get the same color, but darker.

Example: Half Intensity AE83FC:

  {0xAE, 0x83, 0xFC} * 0.5 = {174, 131, 252} * 0.5 = {87, 65, 126} = {0x57, 0x41, 0x7E} => 57417E 

In the same way, you can get brighter versions by multiplying by something> 1. The value of each component cannot be greater than 255, so when this happens, you need to limit it to 255. This means that the color will not be exactly brighter version of the same color, but probably close enough for your purposes.

0
source share

All Articles