案例地址:GitHub - microsoft/WPF-Samples: Repository for WPF related samples
一、运行界面
二、案例功能描述
展示颜色的十六进制值、透明度和红绿蓝的设置、色彩模型的设置;
可自定义颜色
三、分析代码
1、通过RGB值获取色彩模式值
int imax = _red, imin = _red;
if (_green > imax) imax = _green;
else if (_green < imin) imin = _green;
if (_blue > imax) imax = _blue;
else if (_blue < imin) imin = _blue;
double max = imax/255.0, min = imin/255.0;
var value = max;
var saturation = (max > 0) ? (max - min)/max : 0.0;
var hue = _hue;
if (imax > imin)
{
var f = 1.0/((max - min)*255.0);
hue = (imax == _red)
? 0.0 + f*(_green - _blue)
: (imax == _green)
? 2.0 + f*(_blue - _red)
: 4.0 + f*(_red - _green);
hue = hue*60.0;
if (hue < 0.0)
hue += 360.0;
}
2、通过色彩模式获取RGB值
double red = 0.0, green = 0.0, blue = 0.0;
if (_saturation == 0.0)
{
red = green = blue = _value;
}
else
{
var h = _hue;
while (h >= 360.0)
h -= 360.0;
h = h/60.0;
var i = (int) h;
var f = h - i;
var r = _value*(1.0 - _saturation);
var s = _value*(1.0 - _saturation*f);
var t = _value*(1.0 - _saturation*(1.0 - f));
switch (i)
{
case 0:
red = _value;
green = t;
blue = r;
break;
case 1:
red = s;
green = _value;
blue = r;
break;
case 2:
red = r;
green = _value;
blue = t;
break;
case 3:
red = r;
green = s;
blue = _value;
break;
case 4:
red = t;
green = r;
blue = _value;
break;
case 5:
red = _value;
green = r;
blue = s;
break;
}
}
byte iRed = (byte) (red*255.0), iGreen = (byte) (green*255.0), iBlue = (byte) (blue*255.0);