1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import sys
import math
import gtk, cairo

class DrawingInterface:
	def __init__(self, area):
		self.main_window = gtk.Window()
		self.draw_area = gtk.DrawingArea()
		
		self.main_window.connect("destroy", self.on_destroy)
		self.draw_area.connect("expose-event", self.on_expose)
		
		self.main_window.add(self.draw_area)
		self.main_window.set_size_request(area.width, area.height)
		
		self.drawing = Drawing()
		
		self.main_window.show_all()
		
	def on_destroy(self, widget):
		gtk.main_quit()
		
	def on_expose(self, widget, event):
		ctx = widget.window.cairo_create()
		self.drawing.draw(ctx, widget.get_allocation())
	
class Drawing:
	def draw(self, ctx, area):
		
		ctx.rectangle(area.x, area.y,
		              area.width, area.height)
		ctx.set_source_rgb(1, 1, 1) # white
		ctx.fill()
		
		self.draw_rounded_rectangle(ctx, 50, 50, area.width - 100, area.height - 100, 30)
		
	def draw_rounded_rectangle(self, ctx, x, y, width, height, corner_radius):
		aspect        = 1.0     # aspect ratio of corner

		radius = corner_radius / aspect
		degrees = math.pi / 180.0

		ctx.new_sub_path()
		ctx.arc(x + width - radius, y + radius, radius, -90 * degrees, 0 * degrees)
		ctx.arc(x + width - radius, y + height - radius, radius, 0 * degrees, 90 * degrees)
		ctx.arc(x + radius, y + height - radius, radius, 90 * degrees, 180 * degrees)
		ctx.arc(x + radius, y + radius, radius, 180 * degrees, 270 * degrees)
		ctx.close_path()

		#ctx.set_source_rgb(0.5, 0.5, 1)
		ctx.set_source(self.get_gradient(width, height))
		ctx.fill_preserve()
		ctx.set_source_rgba(0.5, 0, 0, 0.5)
		ctx.set_line_width(10.0)
		ctx.stroke()
		
	def get_gradient(self, width, height):
		pattern = cairo.LinearGradient(0, 0, width, height)
		
		pattern.add_color_stop_rgb(0, 0.5, 0.5, 1)
		pattern.add_color_stop_rgb(1, 0.4, 0.7, 1)
		
		return pattern

		
if __name__ == "__main__":
	drawing = Drawing()
	
	arg = None
	if sys.argv[1:]:
		arg = sys.argv[1]
	
	area = gtk.gdk.Rectangle(0, 0, 600, 400)
	
	if arg == 'pdf':
		surface = cairo.PDFSurface("cairo_drawing.pdf", area.width, area.height)
		ctx = cairo.Context(surface)
		drawing.draw(ctx, area)
		
	elif arg == 'png':
		surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, area.width, area.height)
		ctx = cairo.Context(surface)
		drawing.draw(ctx, area)
		surface.write_to_png("cairo_drawing.png")
		
	elif arg == 'svg':
		surface = cairo.SVGSurface("cairo_drawing.svg", area.width, area.height)
		ctx = cairo.Context(surface)
		drawing.draw(ctx, area)
		
	else:
		DrawingInterface(area)
		gtk.main()