在Python中生成颜色渐变

2024-05-26 04:24:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个RGB颜色列表,需要在它们之间用python绘制渐变。你有什么建议,如何使它在皮尔图书馆?

编辑: 我明白了:

def gradient(list_of_colors):
    width = 600
    height = 480
    img = Image.new("RGB", (width, height))
    draw = ImageDraw.Draw(img)

    for i in range(len(list_of_colors)):
        r1,g1,b1 = list_of_colors[i]
        for x in range(width/len(list_of_colors)):
            colour = (r1,g1,b1)
            draw.line((x+(width/len(list_of_colors)*i), 0, x+(width/len(list_of_colors)*i), height), fill=colour)

    img.show()

gradient([(30, 198, 244), (99, 200, 72),(120, 50, 80),(200, 90, 140)])

它让我想到: http://img59.imageshack.us/img59/1852/3gba.png

我只需要在这些颜色之间渐变,而不是条纹。 (类似这样的东西)http://www.kees-tm.nl/uploads/colorgradient.jpg


Tags: ofinimgforlen颜色rangergb
1条回答
网友
1楼 · 发布于 2024-05-26 04:24:03

我认为这样的代码可以工作,它使用Linear Interpolation来创建渐变。

list_of_colors = [(30, 198, 244), (99, 200, 72),(120, 50, 80),(200, 90, 140)]

no_steps = 100

def LerpColour(c1,c2,t):
    return (c1[0]+(c2[0]-c1[0])*t,c1[1]+(c2[1]-c1[1])*t,c1[2]+(c2[2]-c1[2])*t)

for i in range(len(list_of_colors)-2):
    for j in range(no_steps):
        colour = LerpColour(list_of_colors[i],list_of_colors[i+1],j/no_steps)

很明显,我不知道你是如何绘制渐变的,所以我让它对你开放,对颜色变量做你喜欢的事情,在for循环中绘制渐变的每一步。:)

另外:我不了解列表生成,所以如果有人可以改进LerpColour函数来使用它,请编辑我的文章:)

编辑- 生成一个列表,在使用PIL绘制时可以轻松地进行迭代:

gradient = []
for i in range(len(list_of_colors)-2):
    for j in range(no_steps):
        gradient.append(LerpColour(list_of_colors[i],list_of_colors[i+1],j/no_steps))

相关问题 更多 >