简体   繁体   English

Python 中十六进制 colors 的字符串格式

[英]String formatting for hex colors in Python

I modified a function from PHP to return a color gradient (http://www.herethere.net/~samson/php/color_gradient/color_gradient_generator.php.txt).我从 PHP 修改了 function 以返回颜色渐变(http://www.herethere.net/~samson/php/color_gradient/color_gradient_generator.ZE1BFD762321E489CEE4AC0B63)。 I am having issues when returning color hex codes ending in 0s.返回以 0 结尾的颜色十六进制代码时遇到问题。 This is the function:这是 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.当我盯着黑色的#000000 运行一个循环时,我只返回 0。第二个代码 f0f0f 也缺少一个 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?关于如何正确格式化返回值以返回 000000 的任何想法?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM