Update colour.py
このコミットが含まれているのは:
コミット
bdad54c4f4
|
@ -1,4 +1,5 @@
|
|||
import hashlib
|
||||
from website.constants import BACKGROUND_COLOUR
|
||||
|
||||
def _contrast(c1, c2):
|
||||
# https://www2.cs.sfu.ca/CourseCentral/820/li/material/RGB-YUV.pdf
|
||||
|
@ -10,9 +11,28 @@ def _contrast(c1, c2):
|
|||
def _distance_sq(c1, c2):
|
||||
return sum((i / 256 - j / 256) ** 2 for i, j in zip(c1, c2))
|
||||
|
||||
def gen_colour(seed, background):
|
||||
def _gen_colour(seed, background=BACKGROUND_COLOUR):
|
||||
'''
|
||||
Returns a colour that with sufficient contrast to the background colour
|
||||
'''
|
||||
while True:
|
||||
seed = hashlib.sha256(seed).digest()
|
||||
colour = seed[:3]
|
||||
if 1.5 < _contrast(colour, background):
|
||||
for i in range(0, len(seed) - len(seed) % 3, 3):
|
||||
colour = seed[i:i+3]
|
||||
if 1.5 < _contrast(colour, background):
|
||||
return colour
|
||||
|
||||
def gen_colour(seed, background=BACKGROUND_COLOUR, *avoid):
|
||||
'''
|
||||
Returns a colour that with sufficient contrast to the background colour
|
||||
Tries to make the colour contrast with all the colours in `avoid`
|
||||
'''
|
||||
best_colour, best_score = None, None
|
||||
for _ in range(16384):
|
||||
colour = _gen_colour(seed, background)
|
||||
score = float('inf') if len(avoid) == 0 else sum(_contrast(colour, c) for c in avoid) / len(avoid)
|
||||
if 1.25 < score:
|
||||
return colour
|
||||
if best_score == None or score > best_score:
|
||||
best_colour = colour
|
||||
return best_colour
|
||||
|
|
読み込み中…
新しいイシューから参照