RGB和HSL相互转换源码VisualFreeBasic版

GDI标准RGB颜色值  :   这是WIn系统编程的 GDI 颜色值, 还有 GDI+值需要自己改造

HSL 值 :自定义的值,主要是为了方便使用,把4个数字合成1个 LONG 数字

同时支持透明值 A ,当然 GDI 一般不用 A值,GDI+ 则必须的。

位运算简单说明:

数值内存结构,可以打开 WIn 里的计算器,切换程序员模式。数字的2进制是 从右到左,从0到31保存的。
Shr 是向右移动几位  ,Shl 是向右移动几位  ,And 是获取几位数值,=255 是 0-7 位数

RGB和HSL相互转换源码VisualFreeBasic版_第1张图片

Function RGBtoHSL_Gdi(GDI_RGB As Long) As Long 'GDI标准RGB颜色转换为 HSL 值
   'GDI标准RGB颜色 32位数 31--0  a是透明度=31--24  B=23--16 G=15--8 R=7--0
   'aHSL 值        32位数 31--0  a是透明度=31--24  H=23--14 S=13--7 L=6--0
   Dim r As Single = (GDI_RGB And 255)        / 255
   Dim g As Single = (GDI_RGB Shr 8 And 255)  / 255
   Dim b As Single = (GDI_RGB Shr 16 And 255) / 255
   Dim a As Long   = GDI_RGB Shr 24  'GDI 一般无透明通道,特殊时使用的。
   Dim As Single m ,v ,h ,s ,l
   m = min(r ,min(g ,b))
   v = max(r ,max(g ,b))
   l = (m + v) / 2.0
   If l > 0 Then
      Dim vm As Single = v - m
      s = vm
      If s > 0.0 Then
         s /= IIf(l <= 0.5 ,v + m ,2.0 - v - m)
         Dim r2 As Single = (v - r) / vm
         Dim g2 As Single = (v - g) / vm
         Dim b2 As Single = (v - b) / vm
         If r = v Then
            h = IIf(g = m ,5.0 + b2 ,1.0 - g2)
         ElseIf g = v Then
            h = IIf(b = m ,1.0 + r2 ,3.0 - b2)
         Else
            h = IIf(r = m ,3.0 + g2 ,5.0 - r2)
         End If
         h /=6
      End If
   End If
   h *= 360
   s *= 100
   l *= 100
   'PrintA h ,s ,l
   Function = (a Shl 24) Or ((CInt(h) And 511) Shl 14) Or ((CInt(s) And 127) Shl 7) Or (CInt(l) And 127)
End Function
Function HSLtoRGB_Gdi(HSLvalue As Long) As Long 'HSL 值转换为 GDI标准RGB颜色
   'GDI标准RGB颜色 32位数 31--0  a是透明度=31--24  B=23--16 G=15--8 R=7--0
   'aHSL 值        32位数 31--0  a是透明度=31--24  H=23--14 S=13--7 L=6--0
   Dim l As Single = (HSLvalue And 127)        / 100
   Dim s As Single = (HSLvalue Shr 7 And 127)  / 100
   Dim h As Single = (HSLvalue Shr 14 And 511) / 360
   Dim a As Long   = HSLvalue Shr 24
   Dim v As Single = IIf(l <= 0.5 ,l * (1 + s) ,l + s - l *s)
   Dim As Single r ,g ,b
   If v > 0 Then
      Dim m  As Single = l       + l - v
      Dim sv As Single = (v - m) / v
      h *= 6.0
      Dim sextant As Integer = Int(h)
      Dim fract   As Single  = h - sextant
      Dim vsf     As Single  = v * sv * fract
      Dim mid1    As Single  = m + vsf
      Dim mid2    As Single = v - vsf
      Select Case sextant
         Case 0
            r = v
            g = mid1
            b = m
         Case 1
            r = mid2
            g = v
            b = m
         Case 2
            r = m
            g = v
            b = mid1
         Case 3
            r = m
            g = mid2
            b = v
         Case 4
            r = mid1
            g = m
            b = v
         Case 5
            r = v
            g = m
            b = mid2
      End Select
   End If
   'PrintA r * 255 ,g * 255 ,b * 255 
   Function = BGRA(r * 255 ,g * 255 ,b * 255 ,a)
End Function

 

你可能感兴趣的:(VisualFreeBasic)