views:

307

answers:

2

i would like to have a trackbar on my form that will correspond to the HUE of the color of the backgruond, given a range of 1 to 360, and another trackbar that will correspond to saturation of the color of the backgruond, within a range of 1 to 50.

+2  A: 

Using the HSVtoRGB procedure found here, you can hook both your TrackBar controls to the same event handler and use this code:

Private Sub tbHUE_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbHUE.Scroll, tbSaturation.Scroll
  Dim r, g, b As Integer
  HSVtoRGB(r, g, b, tbHUE.Value, tbSaturation.Value / 50, 255)
  BackColor = Color.FromArgb(r, g, b)
End Sub

Edit: Here is the corrected procedure since the one in the link doesn't really follow best practices:

Private Sub HSVtoRGB(ByRef Red As Integer, ByRef Green As Integer, ByRef Blue As Integer, ByVal Hue As Double, ByVal Sat As Double, ByVal Value As Integer)
  Dim i As Integer
  Dim f As Double, p As Double, q As Double, t As Double

  If Sat = 0 Then
    Red = Value
    Green = Value
    Blue = Value
    Exit Sub
  End If

  i = CInt(Hue) \ 60
  Hue = Hue / 60
  f = Hue - i
  p = Value * (1 - Sat)
  q = Value * (1 - Sat * f)
  t = Value * (1 - Sat * (1 - f))

  Select Case i
    Case 0
      Red = Value
      Green = CInt(t)
      Blue = CInt(p)
    Case 1
      Red = CInt(q)
      Green = Value
      Blue = CInt(p)
    Case 2
      Red = CInt(p)
      Green = Value
      Blue = CInt(t)
    Case 3
      Red = CInt(p)
      Green = CInt(q)
      Blue = Value
    Case 4
      Red = CInt(t)
      Green = CInt(p)
      Blue = Value
    Case 5
      Red = Value
      Green = CInt(p)
      Blue = CInt(q)
  End Select
End Sub
Julien Poulin
julien thank you very much. i am having trouble and getting errors because the code on the webpage is not .NET. for the following: Private Sub UnRGB(ByVal Color As OLE_COLOR, ByRef r, ByRef g, ByRef b) ------- it doesnt know what OLE_COLOR is and for the r, g, and b, it says Error All parameters must be explicitly typed if any of them are explicitly typed
I__
now i am getting Error 4 Operator 'And' is not defined for types 'System.Drawing.Color' and 'Integer'.
I__
Ha yes, the procedure in the link assumes you have 'Option Explicit' off, I'll include the code to make it easier
Julien Poulin
julien thank u very much
I__
+1  A: 

Julien has a good answer, but this will come up in searches, so lots of links always helps :-)

Bob Powell also has some HSL code in his RGB and HSL Colour Space Conversions.

And, (this one's in c# so probably won't help so much), Chris Jackson has some HSB code that looks reasonable. The vb.net port that was linked is, uhm, notsogood, it has issues with option strict turned on. Not insurmountable, but not copypaste ready either

Dan F