Skip to content

Commit

Permalink
Fix darken/lighten
Browse files Browse the repository at this point in the history
  • Loading branch information
paradoxxxzero committed Jun 18, 2013
1 parent a50bfaa commit b822892
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 12 deletions.
16 changes: 5 additions & 11 deletions pygal/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@
Charts styling
"""
from __future__ import division
from pygal.util import cycle_fill
from colorsys import rgb_to_hls, hls_to_rgb
from pygal.util import cycle_fill, rgb_to_hsl, hsl_to_rgb


def darken(color, percent):
Expand All @@ -30,15 +29,10 @@ def darken(color, percent):
assert len(color) in (3, 6), '#rrggbb and #rgb format are supported'
if len(color) == 3:
color = [a for b in zip(color, color) for a in b]

return '#%02x%02x%02x' % tuple(
map(lambda x: 255 * x,
hls_to_rgb(*(
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])))
))))
return '#%02x%02x%02x' % hsl_to_rgb(
*(lambda h, s, l: (h, s, max(0, min(100, l - percent))))(
*rgb_to_hsl(*map(lambda x: int(''.join(x), 16),
zip(color[::2], color[1::2])))))


def lighten(color, percent):
Expand Down
2 changes: 1 addition & 1 deletion pygal/test/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from pygal._compat import u
from pygal.util import (
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


Expand Down
51 changes: 51 additions & 0 deletions pygal/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -382,3 +382,54 @@ def split_title(title, width, title_fs):
title = title[i:].strip()
titles.append(title)
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

0 comments on commit b822892

Please sign in to comment.