将HSB转换为RGB

时间:2015-04-23 19:10:09

标签: c# math colors rgb hsb

我正在创建一个WindowsForm应用程序,它可以获取我输入的HSB值并将它们转换为RGB值。我在这里改编了JDB和Mohsen的答案:HSL to RGB color conversion

我的结果代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;

namespace Colour_Picker
{
    public class HSBToRGB
    {
        public static Color HSBToRGBConversion(float hue, float saturation, float brightness)
        {
        float red, green, blue;

        if(saturation == 0){
            red = green = blue = brightness; // achromatic
        }else{
            var q = brightness < 0.5 ? brightness * (1 + saturation) : brightness + saturation - brightness * saturation;
            var p = 2 * brightness - q;
            red = hue2rgb(p, q, hue + 1f/3);
            green = hue2rgb(p, q, hue);
            blue = hue2rgb(p, q, hue - 1f/3);
        }

        return Color.FromArgb((int)Math.Round(red * 255), (int)Math.Round(green * 255), (int)Math.Round(blue * 255));
        }

        public static float hue2rgb(float p, float q, float t){
            if(t < 0) t += 1;
            if(t > 1) t -= 1;
            if(t < 1f/6) return p + (q - p) * 6 * t;
            if(t < 1f/2) return q;
            if(t < 2f/3) return p + (q - p) * (2f/3 - t) * 6;
            return p;
        }
    }
}

在源中提到HSB值应该在[0,1]的集合中 理想情况下,我希望H在集合[0,360]中,S和B在集合[0,100]中。我试过弄乱hue2rgb,但它不起作用。如何设置我想要的限制?

编辑:感谢TaW帮助我解决原始代码中的错误。我实际上将类中的限制保持为[0,1],但我在调用方法之前从我想要的限制中操作HSB值。

0 个答案:

没有答案