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
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()
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)
stroke=False, stroke_color=[0, 0, 0, 0.5]):
cr = self.cr
+ # the position of the center of a rectangle at (0,0)
mx = width / 2.0
my = height / 2.0
+ # calculate the position of the bottom-left corner after rotating the
+ # rectangle around the center
rx = cx - (mx * cos(theta) - my * sin(theta))
ry = cy - (mx * sin(theta) + my * cos(theta))
- cr.save()
- cr.translate(rx, ry)
- cr.rotate(theta)
-
- if fill:
- cr.rectangle(0, 0, width, height)
- r, g, b, a = self.color_to_rgba(fill_color)
- cr.set_source_rgba(r, g, b, a)
- cr.fill()
-
- if stroke:
- cr.rectangle(0, 0, width, height)
- r, g, b, a = self.color_to_rgba(stroke_color)
- cr.set_source_rgba(r, g, b, a)
- cr.stroke()
- self.draw_dot(0, 0, 3.0, stroke_color)
-
- cr.restore()
+ self.draw_rect(rx, ry, width, height, theta, fill, fill_color, stroke,
+ stroke_color)
def draw_rect(self, x, y, width, height, theta=0, fill=True, fill_color=[1, 1, 1, 0.8],
stroke=False, stroke_color=[0, 0, 0, 0.5]):
diagram.draw_line(0, y, 400, y, [0, 0, 1, 0.2])
+ diagram.draw_rect(40, 40, 300, 100, stroke=True)
+ diagram.draw_rect(40, 40, 300, 100, pi / 30, stroke=True)
+
+ diagram.draw_rect(40, 250, 300, 100, stroke=True)
+ diagram.draw_rect_from_center(40 + 150, 250 + 50, 300, 100, theta=pi / 40, stroke=True, stroke_color=[1, 0, 0], fill=False)
+
diagram.show()