开发者

String formatting for hex colors in Python

开发者 https://www.devze.com 2023-03-17 12:14 出处:网络
I modified a function from PHP to return a color gradient (http://www.herethere.net/~samson/php/color_gradient/color_gradient_generator.php.txt). I am having issues when returning color hex codes endi

I modified a function from PHP to return a color gradient (http://www.herethere.net/~samson/php/color_gradient/color_gradient_generator.php.txt). I am having issues when returning color hex codes ending in 0s. This is the function:

def _get_color(current_step=0, start='000000', end='ffffff', max_steps=16):
    '''
        Returns the color code for current_step between start and end
    '''
    start = '{0:#x}'.format(int(start, 16))
    end = '{0:#x}'.format(int(end, 16))

    if int(max_steps) > 0 & int(max_steps) < 256:
        max_steps = max_steps
    else:
       max_steps = 16

    r0 = (int(start, 16) & 0xff0000) >> 16
    g0 = (int(start, 16) & 0x00ff00) >> 8
    b0 = (int(start, 16) & 0x0000ff) >> 0

    r1 = (int(end, 16) & 0xff0000) >> 16
    g1 = (int(end, 16) & 0x00ff00) >> 8
    b1 = (int(end, 16) & 0x0000ff) >> 0

    if r0 < r1:
        r = int(((r1-r0)*(float(current_step)/float(max_steps)))+r0)
    else:
        r = int(((r0-r1)*(1-(float(current_step)/float(max_steps))))+r1)

    if g0 < g1:
        g = int(((g1-g0)*(float(current_step)/float(max_steps)))+g0)
    else:
        g = int(((g0-g1)*(1-(float(current_step)/float(max_steps))))+g1)

    if b0 < b1:
        b = int(((b1-b0)*(float(current_step)/float(max_steps)))+b0)
    else:
        b = int(((b0-b1)*(1-(float(current_step)/float(max_steps))))+b1)

    return '{0:#x}'.format(((((r << 8) | g) << 8) | b))

When I run a loop staring at #000000 which is black, I only return 0. The second code, f0f0f, is also missing a 0.

for i in range(0, 16):
    print _get_color(current_step=i, start='000000', end='ffffff', max_steps=16)

0
f0f0f
1f1f1f
2f2f2f
3f3f3f
4f4f4f
5f5f5f
6f6f6f
7f7f7f
8f8f8f
9f9f9f
afafaf
bfbfbf
cfcfcf开发者_高级运维
dfdfdf
efefef

Notice the first two hex codes. Any thoughts on how to format the return value properly to return 000000?


>>> print '{0:06x}'.format(123)
00007b
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号