我修改了PHP中的函数以返回颜色渐变(http://www.herethere.net/~samson/php/color_gradient/color_gradient_generator.php.txt)。返回以0结尾的颜色十六进制代码时出现问题。这是功能:
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))
当我运行一个盯着#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
注意前两个十六进制代码。关于如何正确格式化返回值以返回000000的任何想法?
答案 0 :(得分:9)
>>> print '{0:06x}'.format(123)
00007b