Live Chat Icon For mobile
Live Chat Icon

How do you translate a HSB color to RGB?

Platform: WinForms| Category: Colors

Here is a routine that does this. Note that the conversion is not precise but very close. (Please do post any better algorithm in our forums).


[C#]
		// This does not seem to yield accurate results, but very close.
		public static void ConvertHSBToRGB(float h, float s, float v, out float r, out float g, out float b)
		{
			if (s == 0f)
			{
				// if s = 0 then h is undefined
				r = v;
				g = v;
				b = v;
			}
			else
			{
				float hue = (float)h;
				if (h == 360.0f)
				{
					hue = 0.0f;
				}
				hue /= 60.0f;
				int i = (int)Math.Floor((double)hue);
				float f = hue - i;
				float p = v * (1.0f - s);
				float q = v * (1.0f - (s * f));
				float t = v * (1.0f - (s * (1 - f)));

				switch(i)
				{
					case 0: r = v; g = t; b = p; break;
					case 1: r = q; g = v; b = p; break;
					case 2: r = p; g = v; b = t; break;
					case 3: r = p; g = q; b = v; break;
					case 4: r = t; g = p; b = v; break;
					case 5: r = v; g = p; b = q; break;

					default: r = 0.0f; g = 0.0f; b = 0.0f; break; /*Trace.Assert(false);*/ // hue out of range
				}
			}
		}
[VB.Net]
Public Shared Sub ConvertHSBToRGB(h As Single, s As Single, v As Single, ByRef r As Single, ByRef g As Single, ByRef b As Single)
      If s = 0F Then
         ’ if s = 0 then h is undefined
         r = v
         g = v
         b = v
      Else
         Dim hue As Single = System.Convert.ToSingle(h)
         If h = 360F Then
            hue = 0F
         End If
         hue /= 60F
         Dim i As Integer = Fix(Math.Floor(System.Convert.ToDouble(hue)))
         Dim f As Single = hue - i
         Dim p As Single = v *(1F - s)
         Dim q As Single = v *(1F - s * f)
         Dim t As Single = v *(1F - s *(1 - f))
         
         Select Case i
            Case 0
               r = v
               g = t
               b = p
            Case 1
               r = q
               g = v
               b = p
            Case 2
               r = p
               g = v
               b = t
            Case 3
               r = p
               g = q
               b = v
            Case 4
               r = t
               g = p
               b = v
            Case 5
               r = v
               g = p
               b = q
            
            Case Else
               r = 0F
               g = 0F
               b = 0F ’Trace.Assert(false);
         ’ hue out of range
         End Select
      End If
   End Sub ’ConvertHSBToRGB

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.