R – implementing a trackbar that will change background color of form

vb.netwinforms

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.

Best Solution

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