1

I'm creating a WindowsForm application that can take my input HSB values and turn them into RGB values. I adapted JDB and Mohsen's answer here: HSL to RGB color conversion

My resulting code is below:

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;
        }
    }
}

It mentions in the source that HSB values should be in the set of [0,1] I would ideally like H to be in the set [0,360] and S and B to be in the set [0,100]. I tried messing with hue2rgb but it didn't work. How can I set the limits I would like?

EDIT: Thank you TaW for the help with the errors in my original code. I am actually keeping the limits in the class as [0, 1] but I'm manipulating the HSB values from my wanted limits before the method is called.

Community
  • 1
  • 1
Chrayfish
  • 157
  • 2
  • 11
  • 1
    For starters you should change `1/3` to `1f/3` etc.. – TaW Apr 23 '15 at 19:35
  • Didn't think that would be needed seeing as I'm declaring floats instead of integers – Chrayfish Apr 23 '15 at 19:43
  • Well, that's not so. `float f = 1f + 1 / 3; Console.WriteLine(f + "");` A common mistake.. – TaW Apr 23 '15 at 19:45
  • okay thanks for pointing this out, but it doesn't help answer my question. – Chrayfish Apr 23 '15 at 20:50
  • Well, actually it does. To scale [0,1] to [0,100] you multiply by 100f and back you divide by 100f. For 360 the same. But as long as your six integer divisions always return 0 the code is not getting anything right.. – TaW Apr 23 '15 at 21:01
  • Working great now. Just need to edit the limits – Chrayfish Apr 23 '15 at 22:04

0 Answers0