add support for rounded rectangles (#161)

pull/170/head
Catherine Holloway 2022-01-25 20:23:04 -05:00 committed by GitHub
parent abd99f0846
commit 6c655ad220
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 4 deletions

View File

@ -84,14 +84,30 @@ def rect2pathd(rect):
The rectangle will start at the (x,y) coordinate specified by the The rectangle will start at the (x,y) coordinate specified by the
rectangle object and proceed counter-clockwise.""" rectangle object and proceed counter-clockwise."""
x0, y0 = float(rect.get('x', 0)), float(rect.get('y', 0)) x, y = float(rect.get('x', 0)), float(rect.get('y', 0))
w, h = float(rect.get('width', 0)), float(rect.get('height', 0)) w, h = float(rect.get('width', 0)), float(rect.get('height', 0))
x1, y1 = x0 + w, y0 if 'rx' in rect or 'ry' in rect:
x2, y2 = x0 + w, y0 + h rx = float(rect.get('rx', 0))
x3, y3 = x0, y0 + h ry = float(rect.get('ry', 0))
d = "M {} {} ".format(x + rx, y) # right of p0
d += "L {} {} ".format(x + w - rx, y) # go to p1
d += "A {} {} 0 0 1 {} {} ".format(rx, ry, x+w, y+ry) # arc for p1
d += "L {} {} ".format(x+w, y+h-ry) # above p2
d += "A {} {} 0 0 1 {} {} ".format(rx, ry, x+w-rx, y+h) # arc for p2
d += "L {} {} ".format(x+rx, y+h) # right of p3
d += "A {} {} 0 0 1 {} {} ".format(rx, ry, x, y+h-ry) # arc for p3
d += "L {} {} ".format(x, y+ry) # below p0
d += "A {} {} 0 0 1 {} {} z".format(rx, ry, x+rx, y) # arc for p0
return d
x0, y0 = x, y
x1, y1 = x + w, y
x2, y2 = x + w, y + h
x3, y3 = x, y + h
d = ("M{} {} L {} {} L {} {} L {} {} z" d = ("M{} {} L {} {} L {} {} L {} {} z"
"".format(x0, y0, x1, y1, x2, y2, x3, y3)) "".format(x0, y0, x1, y1, x2, y2, x3, y3))
return d return d

View File

@ -3,6 +3,8 @@ import unittest
from svgpathtools import * from svgpathtools import *
from os.path import join, dirname from os.path import join, dirname
from svgpathtools.svg_to_paths import rect2pathd
class TestSVG2Paths(unittest.TestCase): class TestSVG2Paths(unittest.TestCase):
def test_svg2paths_polygons(self): def test_svg2paths_polygons(self):
@ -50,3 +52,9 @@ class TestSVG2Paths(unittest.TestCase):
self.assertTrue(len(path_circle)==2) self.assertTrue(len(path_circle)==2)
self.assertTrue(path_circle==path_circle_correct) self.assertTrue(path_circle==path_circle_correct)
self.assertTrue(path_circle.isclosed()) self.assertTrue(path_circle.isclosed())
def test_rect2pathd(self):
non_rounded = {"x":"10", "y":"10", "width":"100","height":"100"}
self.assertEqual(rect2pathd(non_rounded), 'M10.0 10.0 L 110.0 10.0 L 110.0 110.0 L 10.0 110.0 z')
rounded = {"x":"10", "y":"10", "width":"100","height":"100", "rx":"15", "ry": "12"}
self.assertEqual(rect2pathd(rounded), "M 25.0 10.0 L 95.0 10.0 A 15.0 12.0 0 0 1 110.0 22.0 L 110.0 98.0 A 15.0 12.0 0 0 1 95.0 110.0 L 25.0 110.0 A 15.0 12.0 0 0 1 10.0 98.0 L 10.0 22.0 A 15.0 12.0 0 0 1 25.0 10.0 z")