iOS HSV颜色选择器
2021-03-20 本文已影响0人
yitez
我们平时使用颜色的时候,大多数都是RGBA模式,最近项目里需要做HSV颜色模式的颜色选择器:
image.png
以上图为例:
H(色调):滑动条颜色从左到右,为0~1变化。
S(饱和度):圆环从左到右,为0~1变化。
V (明亮度):圆环从上到下(图中黑色位于下面),为1~0变化。
HSV的色值可以和RGB进行互相转化,固定公式。
#mark RGB转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也提供了相应的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