要设置 Hue,您可以创建一个新的Color,可能是使用GetHue和从给定的一个GetSaturation。getBrightness功能见下!
我正在使用这个:
Color SetHue(Color oldColor)
{
var temp = new HSV();
temp.h = oldColor.GetHue();
temp.s = oldColor.GetSaturation();
temp.v = getBrightness(oldColor);
return ColorFromHSL(temp);
}
// A common triple float struct for both HSL & HSV
// Actually this should be immutable and have a nice constructor!!
public struct HSV { public float h; public float s; public float v;}
// the Color Converter
static public Color ColorFromHSL(HSV hsl)
{
if (hsl.s == 0)
{ int L = (int)hsl.v; return Color.FromArgb(255, L, L, L); }
double min, max, h;
h = hsl.h / 360d;
max = hsl.v < 0.5d ? hsl.v * (1 + hsl.s) : (hsl.v + hsl.s) - (hsl.v * hsl.s);
min = (hsl.v * 2d) - max;
Color c = Color.FromArgb(255, (int)(255 * RGBChannelFromHue(min, max,h + 1 / 3d)),
(int)(255 * RGBChannelFromHue(min, max,h)),
(int)(255 * RGBChannelFromHue(min, max,h - 1 / 3d)));
return c;
}
static double RGBChannelFromHue(double m1, double m2, double h)
{
h = (h + 1d) % 1d;
if (h < 0) h += 1;
if (h * 6 < 1) return m1 + (m2 - m1) * 6 * h;
else if (h * 2 < 1) return m2;
else if (h * 3 < 2) return m1 + (m2 - m1) * 6 * (2d / 3d - h);
else return m1;
}
Run Code Online (Sandbox Code Playgroud)
不要使用内置GetBrightness方法!它为红色、品红色、青色、蓝色和黄色 (!) 返回相同的值 (0.5f)。这个更好:
// color brightness as perceived:
float getBrightness(Color c)
{ return (c.R * 0.299f + c.G * 0.587f + c.B *0.114f) / 256f; }
Run Code Online (Sandbox Code Playgroud)
Ego*_*rov -1
System.Drawing.Color是一种值类型,几乎总是不可变的,尤其是在框架中。这就是为什么你不能setHue使用它,你只能用你需要的字段构造一个新的值类型。
因此,如果您有一个函数可以为您的 HSB 值提供 RGB 值,您可以这样做
Color oldColor = ...;
int red, green, blue;
FromHSB(oldColor.GetHue(), oldColor.GetSaturation(), oldColor.GetBrightness(), out red, out green out blue);
Color newColor = Color.FromArgb(oldColor.A, red, green, blue);
Run Code Online (Sandbox Code Playgroud)
哪里FromHSB看起来像这样
void FromHSB(float hue, float saturation, float brightness, out int red, out int green, out int blue)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6687 次 |
| 最近记录: |