Friday, July 11, 2008

simple graphics with svg


As described in the Wikipedia article, Scalable Vector Graphics (SVG) is a specification for XML that allows simple 2D graphics. It provides a nice alternative to other methods for producing graphics under OS X, because the files can be viewed as text with any text editor, while Safari and other browsers render them as graphics. To convert to another format, just take a screenshot. Other methods are available, including PyObjC / Cocoa and wxpython, but SVG is extremely simple.

Here is a script with Python code to write an SVG file and display it using Safari. The first section just contains boilerplate text needed in our svg file. Next, we define functions to generate the code for circles and rectangles, as well as text. In the last section, we define two functions to write the output file and automatically call Safari to show the graphic.

The following lines are the only specific code for our example (except that the opacity of the blue rectangle was set to 0.6 in the function makeRect).

c = makeCircle(x=150,y=150,radius=75,fill='red')
r = makeRect(x=140,y=120,w=250,h=250,rx=40,
fill='blue')
t = makeText(x=50,y=50,
font='Verdana',size=36,fill='purple',
text='Hello SVG world!\n')

The image is a png screenshot since blogger doesn't support svg. The actual svg file looks like this: