From 6c655ad2200dae008e315bcdc05b5f73a8daeb35 Mon Sep 17 00:00:00 2001 From: Catherine Holloway Date: Tue, 25 Jan 2022 20:23:04 -0500 Subject: [PATCH] add support for rounded rectangles (#161) --- svgpathtools/svg_to_paths.py | 24 ++++++++++++++++++++---- test/test_svg2paths.py | 8 ++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/svgpathtools/svg_to_paths.py b/svgpathtools/svg_to_paths.py index 2dff80a..bcd23a9 100644 --- a/svgpathtools/svg_to_paths.py +++ b/svgpathtools/svg_to_paths.py @@ -84,14 +84,30 @@ def rect2pathd(rect): The rectangle will start at the (x,y) coordinate specified by the 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)) - x1, y1 = x0 + w, y0 - x2, y2 = x0 + w, y0 + h - x3, y3 = x0, y0 + h + if 'rx' in rect or 'ry' in rect: + rx = float(rect.get('rx', 0)) + 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" "".format(x0, y0, x1, y1, x2, y2, x3, y3)) + return d diff --git a/test/test_svg2paths.py b/test/test_svg2paths.py index 90a23e0..5a0dab0 100644 --- a/test/test_svg2paths.py +++ b/test/test_svg2paths.py @@ -3,6 +3,8 @@ import unittest from svgpathtools import * from os.path import join, dirname +from svgpathtools.svg_to_paths import rect2pathd + class TestSVG2Paths(unittest.TestCase): def test_svg2paths_polygons(self): @@ -50,3 +52,9 @@ class TestSVG2Paths(unittest.TestCase): self.assertTrue(len(path_circle)==2) self.assertTrue(path_circle==path_circle_correct) 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") \ No newline at end of file