Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

iphone - Objective-C RGB to HSB

Let's say I've got the colour FF0000, which is red. Finding a darker colour is easy, I just type maybe CC instead of the FF, but let's say I've got the colour AE83FC, which is a complicated colour, how the heck would I find a lighter or darker version of it automatically?

I figured the easy way to do this is to convert my RGB to HSB [Hue, Saturation, Brightness]

How would I do that in Objective-C?

Let's say I've got a RGB which is: 1.0, 0.0, 0.0. That's red.

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

How would I convert that to HSB and then transform the colors and make it go back to RGB to I can use CGContextRGBSetFillColor?

Are there any HSB functions?

Please help. :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, please be aware that three numbers don't describe a color, three numbers together with a colorspace do. RGB isn't a colorspace, it's what's called a color model. There are lots of colorspaces with the RGB model. So ((1,0,0), sRGB) is a different color than ((1,0,0), Adobe RGB). Are you aware of how string encodings work, where a bunch of bytes by itself is not a string? It's a lot like that. It's also similar in that you're kind of asking for trouble whenever you want to look at the component values, because it's an opportunity for messing up the colorspace handling.

Sorry, cannot help myself. Anyway, I'll 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, only those in two specific colorspaces, see docs. You already know you're good if you created the colors yourself with the methods above. If you have a color of unknown provenance, you can (attempt to) convert it to a colorspace in which you can use those component methods with -[NSColor colorUsingColorspaceName:].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...