RGB value to HSL converter

前端 未结 4 1951
余生分开走
余生分开走 2021-01-12 04:12

Google maps api v3 allows \"styles\" to be applied to the map, including setting the color of various features. However, the color format it uses is HSL (or what seems like

4条回答
  •  长情又很酷
    2021-01-12 04:49

    Since the hue argument expects RGB, you can use the original color as the hue.

    rgb2hsl.py:

    #!/usr/bin/env python
    
    def rgb2hsl(r, g, b):
        #Hue: the RGB string
        H = (r<<16) + (g<<8) + b
        H = "0x%06X" % H
    
        #convert to [0 - 1] range
        r = float(r) / 0xFF
        g = float(g) / 0xFF
        b = float(b) / 0xFF
    
        #http://en.wikipedia.org/wiki/HSL_and_HSV#Lightness
        M = max(r,g,b)
        m = min(r,g,b)
        C = M - m
    
        #Lightness
        L = (M + m) / 2
    
        #Saturation (HSL)
        if L == 0:
            S = 0
        elif L <= .5:
            S = C/(2*L)
        else:
            S = C/(2 - 2*L)
    
        #gmaps wants values from -100 to 100
        S = int(round(S * 200 - 100))
        L = int(round(L * 200 - 100))
    
        return (H, S, L)
    
    
    def main(r, g, b):
        r = int(r, base=16)
        g = int(g, base=16)
        b = int(b, base=16)
        print rgb2hsl(r,g,b)
    
    if __name__ == '__main__':
        from sys import argv
        main(*argv[1:])
    

    Example:

    $ ./rgb2hsl.py F0 FF FF
    ('0xF0FFFF', 100, 94)
    

    Result:

    Below is a screenshot showing the body set to a rgb background color (#2800E2 in this case), and a google map with styled road-geometry, using the values calculated as above ('0x2800E2', 100, -11).

    It's pretty clear that google uses your styling to create around six different colors centered on the given color, with the outlines being closest to the input. I believe this is as close as it gets.

    alt text


    From experimentation with: http://gmaps-samples-v3.googlecode.com/svn/trunk/styledmaps/wizard/index.html

    For water, gmaps subtracts a gamma of .5. To get the exact color you want, use the calculations above, and add that .5 gamma back.

    like:

    {
      featureType: "water",
      elementType: "geometry",
      stylers: [
        { hue: "#2800e2" },
        { saturation: 100 },
        { lightness: -11 },
        { gamma: 0.5 },
      ]
    }
    

提交回复
热议问题