Skip to content

Commit

Permalink
Set fill and stroke opacity from color alpha
Browse files Browse the repository at this point in the history
Thanks Chris Buergi for the initial patch.
claudep committed Jan 20, 2022
1 parent 8486274 commit f269678
Showing 3 changed files with 31 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
@@ -8,6 +8,8 @@ Unreleased

- dropped support for Python 3.6 and added official support for Python 3.10.
- improved support for scientific notation in paths (#277)
- if some path has a color with alpha value, it also sets the default fill or
stroke opacity of the resulting object.

1.1.0 (2021-04-10)
------------------
14 changes: 13 additions & 1 deletion svglib/svglib.py
Original file line number Diff line number Diff line change
@@ -368,7 +368,7 @@ def convertColor(self, svgAttr):
if color is None:
# Test if text is a predefined color constant
try:
color = getattr(colors, text)
color = getattr(colors, text).clone()
except AttributeError:
pass
if color is None:
@@ -1386,6 +1386,18 @@ def applyStyleOnShape(self, shape, node, only_explicit=False):
if svgAttrValue == '':
if only_explicit:
continue
if (
svgAttrName == 'fill-opacity'
and getattr(shape, 'fillColor', None) is not None
and getattr(shape.fillColor, 'alpha', 1) != 1
):
svgAttrValue = shape.fillColor.alpha
elif (
svgAttrName == 'stroke-opacity'
and getattr(shape, 'strokeColor', None) is not None
and getattr(shape.strokeColor, 'alpha', 1) != 1
):
svgAttrValue = shape.strokeColor.alpha
else:
svgAttrValue = defaults[index]
if svgAttrValue == "currentColor":
16 changes: 16 additions & 0 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
@@ -436,6 +436,22 @@ def test_fillopacity(self):
''')))
assert drawing.contents[0].contents[0].fillColor == colors.Color(0, 0, 0, 0)

def test_fillcolor_alpha_set_fillopacity(self):
converter = svglib.Svg2RlgShapeConverter(None)
node = etree.XML('<polygon fill="#ff000080"/>')
poly = Polygon()
converter.applyStyleOnShape(poly, node)
assert poly.fillOpacity == 128 / 255
assert poly.strokeOpacity == 1

def test_strokecolor_alpha_set_strokeopacity(self):
converter = svglib.Svg2RlgShapeConverter(None)
node = etree.XML('<polygon stroke="#cccccca0"/>')
poly = Polygon()
converter.applyStyleOnShape(poly, node)
assert poly.fillOpacity == 1
assert poly.strokeOpacity == 160 / 255

def test_fillrule(self):
converter = svglib.Svg2RlgShapeConverter(None)
node = etree.XML('<polygon fill-rule="evenodd"/>')

0 comments on commit f269678

Please sign in to comment.