Browse Source

Fix darken/lighten

pull/35/merge
Florian Mounier 12 years ago
parent
commit
b822892a89
  1. 16
      pygal/style.py
  2. 2
      pygal/test/test_util.py
  3. 51
      pygal/util.py

16
pygal/style.py

@ -20,8 +20,7 @@
Charts styling Charts styling
""" """
from __future__ import division from __future__ import division
from pygal.util import cycle_fill from pygal.util import cycle_fill, rgb_to_hsl, hsl_to_rgb
from colorsys import rgb_to_hls, hls_to_rgb
def darken(color, percent): def darken(color, percent):
@ -30,15 +29,10 @@ def darken(color, percent):
assert len(color) in (3, 6), '#rrggbb and #rgb format are supported' assert len(color) in (3, 6), '#rrggbb and #rgb format are supported'
if len(color) == 3: if len(color) == 3:
color = [a for b in zip(color, color) for a in b] color = [a for b in zip(color, color) for a in b]
return '#%02x%02x%02x' % hsl_to_rgb(
return '#%02x%02x%02x' % tuple( *(lambda h, s, l: (h, s, max(0, min(100, l - percent))))(
map(lambda x: 255 * x, *rgb_to_hsl(*map(lambda x: int(''.join(x), 16),
hls_to_rgb(*( zip(color[::2], color[1::2])))))
lambda h, l, s: (h, max(0, min(1, l - percent / 100)), s))(
*rgb_to_hls(*map(
lambda x: int(''.join(x), 16) / 255,
zip(color[::2], color[1::2])))
))))
def lighten(color, percent): def lighten(color, percent):

2
pygal/test/test_util.py

@ -19,7 +19,7 @@
from pygal._compat import u from pygal._compat import u
from pygal.util import ( from pygal.util import (
round_to_int, round_to_float, _swap_curly, template, humanize, round_to_int, round_to_float, _swap_curly, template, humanize,
is_major, truncate, minify_css) is_major, truncate, minify_css, rgb_to_hsl, hsl_to_rgb)
from pytest import raises from pytest import raises

51
pygal/util.py

@ -382,3 +382,54 @@ def split_title(title, width, title_fs):
title = title[i:].strip() title = title[i:].strip()
titles.append(title) titles.append(title)
return titles return titles
def rgb_to_hsl(r, g, b):
r /= 255
g /= 255
b /= 255
max_ = max((r, g, b))
min_ = min((r, g, b))
d = max_ - min_
if not d:
h = 0
elif r is max_:
h = 60 * (g - b) / d
elif g is max_:
h = 60 * (b - r) / d + 120
else:
h = 60 * (r - g) / d + 240
l = .5 * (max_ + min_)
if not d:
s = 0
elif l < 0.5:
s = .5 * d / l
else:
s = .5 * d / (1 - l)
return h % 360, s * 100, l * 100
def hsl_to_rgb(h, s, l):
h /= 360
s /= 100
l /= 100
m2 = l * (s + 1) if l <= .5 else l + s - l * s
m1 = 2 * l - m2
def h_to_rgb(h):
h = h % 1
if 6 * h < 1:
return m1 + 6 * h * (m2 - m1)
if 2 * h < 1:
return m2
if 3 * h < 2:
return m1 + 6 * (2 / 3 - h) * (m2 - m1)
return m1
r, g, b = map(lambda x: round(x * 255),
map(h_to_rgb, (h + 1 / 3, h, h - 1 / 3)))
return r, g, b

Loading…
Cancel
Save