您的位置:首页 > 产品设计 > UI/UE

UIColor:RGB和HSV互相转换

2014-05-14 11:40 1106 查看
UIColor:RGB和HSV互相转换

关于颜色的种种属性,一直感觉挺神秘,不曾花时间来研究,今天揭开神秘面纱的一角。
RGB:三原色
Red, Green, Blue
Alpha:不透明度
HSV :
H  -   Hue            色度
S  -   Saturation   彩度
V  -   Brightness   亮度

关于RGB和HSV互相转换,iOS编程中的颜色处理中,时常会用到。
参考资料:
How do i get the hue, saturation and brightness from a UIColor?

例子代码:
static void RGBtoHSV( float r, float g, float b, float *h, float *s, float *v )
{
float min, max, delta;
min = MIN( r, MIN( g, b ));
max = MAX( r, MAX( g, b ));
*v = max;               // v
delta = max - min;
if( max != 0 )
*s = delta / max;       // s
else {
// r = g = b = 0        // s = 0, v is undefined
*s = 0;
*h = -1;
return;
}
if( r == max )
*h = ( g - b ) / delta;     // between yellow & magenta
else if( g == max )
*h = 2 + ( b - r ) / delta; // between cyan & yellow
else
*h = 4 + ( r - g ) / delta; // between magenta & cyan
*h *= 60;               // degrees
if( *h < 0 )
*h += 360;
}

static void HSVtoRGB( float *r, float *g, float *b, float h, float s, float v )
{
int i;
float f, p, q, t;
if( s == 0 ) {
// achromatic (grey)
*r = *g = *b = v;
return;
}
h /= 60;            // sector 0 to 5
i = floor( h );
f = h - i;          // factorial part of h
p = v * ( 1 - s );
q = v * ( 1 - s * f );
t = v * ( 1 - s * ( 1 - f ) );
switch( i ) {
case 0:
*r = v;
*g = t;
*b = p;
break;
case 1:
*r = q;
*g = v;
*b = p;
break;
case 2:
*r = p;
*g = v;
*b = t;
break;
case 3:
*r = p;
*g = q;
*b = v;
break;
case 4:
*r = t;
*g = p;
*b = v;
break;
default:        // case 5:
*r = v;
*g = p;
*b = q;
break;
}
}

...

CGFloat r, g, b, a, h, s, v;

const CGFloat *comp = CGColorGetComponents([myUIColor CGColor]);

r = comp[0];
g = comp[1];
b = comp[2];
a = comp[3];

RGBtoHSV(r, g, b, &h, &s, &v);


UIColor设置自定义的颜色不成功问题

RGBA是0.0~1.0,不是0~255

在iOS的开发中经常用到一个对象UIColor,这个对象提供了一个通过RGBA来设置颜色的方法:[UIColor colorWithRed: green: blue: alpha:];

但是在使用这个方法的时候很多人会遇到设置的颜色不成功的问题,下面就来说明一下使用这个方法应注意的问题点:

1.这个方法中RGBA的值都是小数;

2.颜色值RGB是通过你的颜色值除以255(0xFF)得来的。

[UIColor colorWithRed:123/255 green:127/255 blue:120/255 alpha:1];这个设置是错误的,因为127/255的结果是整数0,而不是我们想要的小数。#000000代表的颜色是黑色。

正确的设置方法应该是:[UIColor colorWithRed:123.0/255 green:127.0/255 blue:120.0/255 alpha:1];

经过验证,上面的说法是正确的  by thanklife
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: