C#setHue(或者,将HSL转换为RGB并设置RGB) [英] C# setHue (or alternatively, convert HSL to RGB and set RGB)

查看:1399
本文介绍了C#setHue(或者,将HSL转换为RGB并设置RGB)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#有一个非常方便的getHue方法,但我找不到设置 Hue方法。有没有一个?

C# has a very convenient getHue method, but I can't find a setHue method. Is there one?

如果没有,我认为更改色调后定义颜色的最佳方法是将HSL值转换为RGB,然后设置RGB值。我知道在互联网上有这样做的公式,但我最好去使用C#执行从HSL到RGB的转换?

If not, I think the best way to define a color after changing the hue would be to convert the HSL value to RGB, and then set the RGB value. I know there are formulas on the internet for doing this, but how would I best go about performing this conversion from HSL to RGB using C#?

谢谢

推荐答案

要设置Hue, Color ,可能是通过使用 GetHue GetSaturation 。请参阅下面的 getBrightness 函数!

To set the Hue you create a new Color, maybe from a given one by using GetHue and GetSaturation. See below for the getBrightness function!

我使用这个:

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;

}

不要使用内置的 GetBrightness 方法!它为红色,品红色,青色,蓝色和黄色(!)返回相同的值(0.5f)。这是更好的:

Do not use the built-in GetBrightness method! It returns the same value (0.5f) for red, magenta, cyan, blue and yellow (!). This is better:

// color brightness as perceived:
float getBrightness(Color c)  
   {  return (c.R * 0.299f + c.G * 0.587f + c.B *0.114f) / 256f; }

这篇关于C#setHue(或者,将HSL转换为RGB并设置RGB)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆