1
2 """\
3 SVG.py - Construct/display SVG scenes.
4
5 The following code is a lightweight wrapper around SVG files. The metaphor
6 is to construct a scene, add objects to it, and then write it to a file
7 to display it.
8
9 This program uses ImageMagick to display the SVG files. ImageMagick also
10 does a remarkable job of converting SVG files into other formats.
11 """
12
13 import os
14 display_prog = 'display'
15
17 - def __init__(self,name="svg",height=400,width=400):
18 self.name = name
19 self.items = []
20 self.height = height
21 self.width = width
22 return
23
25
27 var = ["<?xml version=\"1.0\"?>\n",
28 "<svg height=\"%d\" width=\"%d\" >\n" % (self.height,self.width),
29 " <g style=\"fill-opacity:1.0; stroke:black;\n",
30 " stroke-width:1;\">\n"]
31 for item in self.items: var += item.strarray()
32 var += [" </g>\n</svg>\n"]
33 return var
34
44
46 os.system("%s %s" % (prog,self.svgname))
47 return
48
49
52 self.start = start
53 self.end = end
54 return
55
57 return [" <line x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" />\n" %\
58 (self.start[0],self.start[1],self.end[0],self.end[1])]
59
60
63 self.center = center
64 self.radius = radius
65 self.color = color
66 return
67
69 return [" <circle cx=\"%d\" cy=\"%d\" r=\"%d\"\n" %\
70 (self.center[0],self.center[1],self.radius),
71 " style=\"fill:%s;\" />\n" % colorstr(self.color)]
72
74 - def __init__(self,origin,height,width,color):
75 self.origin = origin
76 self.height = height
77 self.width = width
78 self.color = color
79 return
80
82 return [" <rect x=\"%d\" y=\"%d\" height=\"%d\"\n" %\
83 (self.origin[0],self.origin[1],self.height),
84 " width=\"%d\" style=\"fill:%s;\" />\n" %\
85 (self.width,colorstr(self.color))]
86
88 - def __init__(self,origin,text,size=24):
89 self.origin = origin
90 self.text = text
91 self.size = size
92 return
93
95 return [" <text x=\"%d\" y=\"%d\" font-size=\"%d\">\n" %\
96 (self.origin[0],self.origin[1],self.size),
97 " %s\n" % self.text,
98 " </text>\n"]
99
100
101 -def colorstr(rgb): return "#%x%x%x" % (rgb[0]/16,rgb[1]/16,rgb[2]/16)
102
104 scene = Scene('test')
105 scene.add(Rectangle((100,100),200,200,(0,255,255)))
106 scene.add(Line((200,200),(200,300)))
107 scene.add(Line((200,200),(300,200)))
108 scene.add(Line((200,200),(100,200)))
109 scene.add(Line((200,200),(200,100)))
110 scene.add(Circle((200,200),30,(0,0,255)))
111 scene.add(Circle((200,300),30,(0,255,0)))
112 scene.add(Circle((300,200),30,(255,0,0)))
113 scene.add(Circle((100,200),30,(255,255,0)))
114 scene.add(Circle((200,100),30,(255,0,255)))
115 scene.add(Text((50,50),"Testing SVG"))
116 scene.write_svg()
117 scene.display()
118 return
119
120 if __name__ == '__main__': test()
121