问题
In my app I am trying to draw with different colors. I have my own color picker, but I want to add to this picker slider for color brightness. For understudying : I choose a color which is displayed somewhere in view as background color and to this color I want add slider which will slide from 1 to 0 and change brightness of the color and displays the color in window. Therefore I want to ask if there is any possible way how to convert.
in my project I use this :
CGContextSetRGBStrokeColor(current, R, G, B, A);
so anytime I slide the slider I need to change the brightness of the color, therefore I need to convert my UIColor - represented as RGB to HSV and than back to RGB for using it one more time.
Does exist any RGB to HSV conversion algorithm or is there any in iOS 5 or Xcode4?
回答1:
+(struct hsv_color)HSVfromRGB:(struct rgb_color)rgb
{
struct hsv_color hsv;
CGFloat rgb_min, rgb_max;
rgb_min = MIN3(rgb.r, rgb.g, rgb.b);
rgb_max = MAX3(rgb.r, rgb.g, rgb.b);
if (rgb_max == rgb_min) {
hsv.hue = 0;
} else if (rgb_max == rgb.r) {
hsv.hue = 60.0f * ((rgb.g - rgb.b) / (rgb_max - rgb_min));
hsv.hue = fmodf(hsv.hue, 360.0f);
} else if (rgb_max == rgb.g) {
hsv.hue = 60.0f * ((rgb.b - rgb.r) / (rgb_max - rgb_min)) + 120.0f;
} else if (rgb_max == rgb.b) {
hsv.hue = 60.0f * ((rgb.r - rgb.g) / (rgb_max - rgb_min)) + 240.0f;
}
hsv.val = rgb_max;
if (rgb_max == 0) {
hsv.sat = 0;
} else {
hsv.sat = 1.0 - (rgb_min / rgb_max);
}
return hsv;
}
回答2:
It's not clear to me if in your original question you really want "brightness" or alpha. RGB and HSV color schemes are completely different.
If I interpret your intent correctly:
You do not need to convert from RGB to HSV and back to RGB if all you want to do is control the alpha channel for an RGB color.
The simplest and most efficient way to achieve what you want to do is to simply add a slider for alpha and take the output from that to change color transparency.
来源:https://stackoverflow.com/questions/9142427/uicolor-conversion-from-rgb-to-hsv-set-brightness-to-uicolor