我們平時(shí)使用顏色的時(shí)候稽坤,大多數(shù)都是RGBA模式丈甸,最近項(xiàng)目里需要做HSV顏色模式的顏色選擇器:
以上圖為例:
H(色調(diào)):滑動(dòng)條顏色從左到右,為0~1變化尿褪。
S(飽和度):圓環(huán)從左到右睦擂,為0~1變化。
V (明亮度):圓環(huán)從上到下(圖中黑色位于下面)杖玲,為1~0變化顿仇。
HSV的色值可以和RGB進(jìn)行互相轉(zhuǎn)化,固定公式。
#mark RGB轉(zhuǎn)HSV
max=max(R,G,B)臼闻;
min=min(R,G,B)鸿吆;
V=max(R,G,B);
S=(max-min)/max述呐;
if (R = max) H =(G-B)/(max-min)* 60惩淳;
if (G = max) H = 120+(B-R)/(max-min)* 60;
if (B = max) H = 240 +(R-G)/(max-min)* 60市埋;
if (H < 0) H = H+ 360黎泣;
#MARK HSV傳RGB
if (s = 0)
R=G=B=V;
else
H /= 60;
i = INTEGER(H);
f = H - i;
a = V * ( 1 - s );
b = V * ( 1 - s * f );
c = V * ( 1 - s * (1 - f ) );
switch(i)
case 0: R = V; G = c; B = a;
case 1: R = b; G = v; B = a;
case 2: R = a; G = v; B = c;
case 3: R = a; G = b; B = v;
case 4: R = c; G = a; B = v;
case 5: R = v; G = a; B = b;
iOS也提供了相應(yīng)的API可以獲取HSV和RGB值的方法恕刘,很方便:
#mark 獲取HSV
var H:CGFloat = 0
var S:CGFloat = 0
var V:CGFloat = 0
var alpha:CGFloat = 0
color.getHue(&H, saturation: &S, brightness: &V, alpha: &alpha)
#mark 獲取RGB
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
color.getRed(&r, green: &g, blue: &b, alpha: &a)
以下為demo地址:
https://github.com/yitezh/YTHSVColorPicker