Diagram.py: fix and simplify drawing polygon fill and stroke
[experiments/RadialSymmetry.git] / Diagram.py
index fa35d32..28cb064 100755 (executable)
@@ -23,7 +23,7 @@ from math import *
 
 class Diagram(object):
 
-    def __init__(self, width, height, background=[1, 1, 1]):
+    def __init__(self, width, height, background=[1, 1, 1], font_size=20):
         self.width = width
         self.height = height
         self.background = background
@@ -38,7 +38,7 @@ class Diagram(object):
 
         cr.select_font_face("Georgia", cairo.FONT_SLANT_NORMAL,
                             cairo.FONT_WEIGHT_NORMAL)
-        cr.set_font_size(20)
+        cr.set_font_size(font_size)
 
         # Adjust the font matrix to left-bottom origin
         M = cr.get_font_matrix()
@@ -97,39 +97,36 @@ class Diagram(object):
         else:
             return None
 
-    def draw_polygon(self, verts, stroke_color=[0, 0, 0], fill_color=None):
+    def _draw_polygon(self, verts):
         cr = self.cr
 
-        if fill_color:
-            v = verts[0]
-            cr.move_to(v[0], v[1])
-            for v in verts[1:]:
-                cr.line_to(v[0], v[1])
-                cr.close_path()
+        v = verts[0]
+        cr.move_to(v[0], v[1])
+        for v in verts[1:]:
+            cr.line_to(v[0], v[1])
+        cr.close_path()
+
+    def draw_polygon(self, verts, fill_color=None, stroke_color=[0, 0, 0]):
+        cr = self.cr
 
+        if fill_color:
+            self._draw_polygon(verts)
             r, g, b, a = self.color_to_rgba(fill_color)
             cr.set_source_rgba(r, g, b, a)
             cr.fill()
 
-        n = len(verts)
-        for i in range(0, n):
-            v1 = verts[i]
-            v2 = verts[(i + 1) % n]
-            cr.move_to(v1[0], v1[1])
-            cr.line_to(v2[0], v2[1])
-
-        r, g, b, a = self.color_to_rgba(stroke_color)
-        cr.set_source_rgba(r, g, b, a)
-        cr.stroke()
+        if stroke_color:
+            self._draw_polygon(verts)
+            r, g, b, a = self.color_to_rgba(stroke_color)
+            cr.set_source_rgba(r, g, b, a)
+            cr.stroke()
 
     def draw_star(self, cx, cy, verts, stroke_color=[0, 0, 0]):
         cr = self.cr
 
-        v = verts[0]
-        cr.move_to(cx, cy)
         for v in verts:
-            cr.line_to(v[0], v[1])
             cr.move_to(cx, cy)
+            cr.line_to(v[0], v[1])
 
         r, g, b, a = self.color_to_rgba(stroke_color)
         cr.set_source_rgba(r, g, b, a)