• Python - 实现渐变色的RGB计算


    一、解决了什么问题:

    求得两个颜色之间颜色渐变的RGB。

    二、公式:

    Gradient = A + (B-A) / Step * N
    编程时为了提高效率避免浮点运算,往往把除法放在最后面,这样公式就成了:Gradient = A + (B-A) * N / Step

    Gradient表示第N步的R/G/B的值,A、B、Step表示从颜色A分Step步渐变为颜色B。

    三、计算过程:

    设Step=3,将RGB(200,50,0)颜色渐变为RGB(50,200,0),即:RGB(200,50,0)经过3次颜色渐变转为RGB(50,200,0)

    第0次转换,即RGB(200,50,0)本身:
    R0 = 200 + (50 - 200) / 3 * 0 = 200
    G0 = 50 + (200 - 50) / 3 * 0 = 50
    B0 = 0 + (0 - 0) / 3 * 0 = 0
    RGB0 = (200, 50, 0)

    第1次转换:
    R1 = 200 + (50 - 200)/ 3 * 1 = 150
    G1 = 50 + (200 - 50) / 3 * 1 = 100
    B1 = 0 + (0 - 0) / 3 * 1 = 0
    RGB1 = (150, 100, 0)

    第2次转换:
    R2 = 200 + (50 - 200)/ 3 * 2 = 100
    G2 = 50 + (200 - 50) / 3 * 2 = 150
    B2 = 0 + (0 - 0) / 3 * 2 = 0
    RBG2 = (100, 150, 0)

    第3次转换,即目标颜色RGB(50,200,0):
    R3 = 200 + (50 - 200)/ 3 * 3 = 50
    G3 = 50 + (200 - 50) / 3 * 3 = 200
    B3 = 0 + (0 - 0) / 3 * 3 = 0
    RBG3 = (50, 200, 0)

    四、代码

    import matplotlib.pyplot as plt
    import numpy as np
    
    step = 3   # 经过step步到达目标颜色
    color_num = step + 1
    one = np.ones(color_num)
    from_rgb = (200,50,0)  # 起始颜色
    to_rbg = (50,200,0)    # 目标颜色
    
    colors = [((from_rgb[0] + (to_rbg[0]-from_rgb[0])/step*i),
              (from_rgb[1] + (to_rbg[1]-from_rgb[1])/step*i),
              (from_rgb[2] + (to_rbg[2]-from_rgb[2])/step*i))
              for i in range(color_num)]
              
    for index, color in enumerate(colors):
        print(index, color)
    
    colors = [((from_rgb[0] + (to_rbg[0]-from_rgb[0])/step*i) / 255,
              (from_rgb[1] + (to_rbg[1]-from_rgb[1])/step*i) / 255,
              (from_rgb[2] + (to_rbg[2]-from_rgb[2])/step*i) / 255)
              for i in range(color_num)]
    
    plt.pie(one, labels=range(color_num), colors=colors)  # colors要求是0-1的浮点数
    plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    结果与颜色展示:
    在这里插入图片描述

    五、举一反三

    下面对step、起始颜色、目标颜色进行修改,细分更多步骤的变化展示。

    例1:
    step = 50
    from_rgb = (193, 214, 6)
    to_rbg = (244, 225, 67)
    在这里插入图片描述


    例2:
    step = 50
    from_rgb = (244, 225, 67)
    to_rbg = (227, 118, 0)
    在这里插入图片描述

    六、参考

    1. 颜色渐变的RGB计算
  • 相关阅读:
    【PAT甲级 - C++题解】1114 Family Property
    从头开始实现一个留言板-README
    Maven学习笔记
    [Cmake Qt]找不到文件ui_xx.h的问题?有关Qt工程的问题,看这篇文章就行了。
    一起Talk Android吧(第四百三十一回:Java8中的日期类)
    【JVM笔记】强引用、软引用、弱引用、虚引用、终结器引用
    华清 Qt day4 9月20
    Alibaba官方上线,SpringBoot+SpringCloud全彩指南(第五版)
    VUE——验证码倒计时
    JavaFX下载
  • 原文地址:https://blog.csdn.net/DreamingBetter/article/details/126872234