1 核心函数
给定一个颜色,自动计算对比度最强的颜色
def get_complementary(color):
# strip the # from the beginning
color = color[1:]
# convert the string into hex
color = int(color, 16)
# invert the three bytes
# as good as substracting each of RGB component by 255(FF)
comp_color = 0xFFFFFF ^ color
# convert the color back to hex by prefixing a #
comp_color = "#%06X" % comp_color
# return the result
return comp_color
2 举一个完整的例子
如黄色:"#FFFF00"
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
def get_complementary(color):
# strip the # from the beginning
color = color[1:]
# convert the string into hex
color = int(color, 16)
# invert the three bytes
# as good as substracting each of RGB component by 255(FF)
comp_color = 0xFFFFFF ^ color
# convert the color back to hex by prefixing a #
comp_color = "#%06X" % comp_color
# return the result
return comp_color
def draw_rectangle(color1):
color2 = get_complementary(color1)
#define Matplotlib figure and axis
fig, ax = plt.subplots()
#create simple line plot
ax.plot([0, 10],[0, 10], alpha=0)
#add rectangle to plot
ax.add_patch(Rectangle((1, 1), 2, 6, color=color1))
ax.add_patch(Rectangle((3, 1), 2, 6, color=color2))
#display plot
plt.show()
print(f"\n----------------------------------------------"
f"Complementary color of '{color1}' is '{color2}'."
f"\n----------------------------------------------")
draw_rectangle("#FFFF00") # yellow
3 运行后得到:
----------------------------------------------
Complementary color of '#FFFF00' is '#0000FF'.
----------------------------------------------