Generating a Random Hex Color in Python

前端 未结 15 1811
悲&欢浪女
悲&欢浪女 2020-11-29 01:36

For a Django App, each \"member\" is assigned a color to help identify them. Their color is stored in the database and then printed/copied into the HTML when it is needed. T

15条回答
  •  忘掉有多难
    2020-11-29 02:16

    Store it as a HTML color value:

    Updated: now accepts both integer (0-255) and float (0.0-1.0) arguments. These will be clamped to their allowed range.

    def htmlcolor(r, g, b):
        def _chkarg(a):
            if isinstance(a, int): # clamp to range 0--255
                if a < 0:
                    a = 0
                elif a > 255:
                    a = 255
            elif isinstance(a, float): # clamp to range 0.0--1.0 and convert to integer 0--255
                if a < 0.0:
                    a = 0
                elif a > 1.0:
                    a = 255
                else:
                    a = int(round(a*255))
            else:
                raise ValueError('Arguments must be integers or floats.')
            return a
        r = _chkarg(r)
        g = _chkarg(g)
        b = _chkarg(b)
        return '#{:02x}{:02x}{:02x}'.format(r,g,b)
    

    Result:

    In [14]: htmlcolor(250,0,0)
    Out[14]: '#fa0000'
    
    In [15]: htmlcolor(127,14,54)
    Out[15]: '#7f0e36'
    
    In [16]: htmlcolor(0.1, 1.0, 0.9)
    Out[16]: '#19ffe5'
    

提交回复
热议问题