Open Technical Blog
Wednesday, 12 September 2012
PyCairo 01
This script shows how to draw simple graphics with Cairo in PyGtk. The following techniques are adopted:
Cairo for graphics.
Draw lines.
Draw rectangles.
Draw circles.
Draw text.
Save the result to a SVG file.
Output
A file named
d01.svg
will be generated by this script on the same directory holding the script, it holds the following diagram.
Source Code
import gtk, cairo import math WIDTH, HEIGHT = 400, 400 # Setup Cairo surface = cairo.SVGSurface("d01.svg", WIDTH, HEIGHT) context = cairo.Context(surface) # Set thickness of brush context.set_line_width(4) context.set_source_rgb(0, 0, 0) # Draw Vertical Line context.move_to(200, 0) context.line_to(200, 400) context.stroke() # Set thickness of brush context.set_line_width(50) # Draw horizontal line context.move_to(0, 200) context.line_to(500, 200) context.stroke() # draw rectangle context.set_line_width(10) context.rectangle(20,70,80,30) context.set_source_rgb(0, 0.5, 0.5) context.stroke_preserve() context.set_source_rgb(0, 0.8, 0.8) context.fill() # draw circle context.set_line_width(20) #context.translate(100,250) context.arc(100,150,60,0,2*math.pi) context.set_source_rgb(0.95, 0.8, 0.8) context.stroke_preserve() context.set_source_rgb(0.9, 0, 0) context.fill() # draw triangle context.set_line_width(4) context.move_to(90,110) context.line_to(50,160) context.line_to(140,180) context.close_path() context.set_source_rgb(1, 1, 1) context.stroke_preserve() context.set_source_rgb(0, 0.6, 0.8) context.fill() # draw text context.move_to(50,50) context.select_font_face('Serif', cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) context.set_font_size(24) context.set_source_rgb(0, 0, 0) context.show_text("Can you see me?") context.stroke() # draw grid using alpha in lines # vertical lines context.set_line_width(2) context.set_source_rgba(0.8, 0.8, 0.8,0.6) for mi in range(0,200,50): context.move_to(mi,0) context.line_to(mi,200) context.stroke() context.move_to(0,mi) context.line_to(200,mi) context.move_to(200,0) context.line_to(200,200) context.move_to(0,200) context.line_to(200,200) context.stroke() # horizontal lines context.set_line_width(1) context.set_source_rgba(0.8, 0.8, 0.8,0.6) for mi in range(0,200,10): context.move_to(mi,0) context.line_to(mi,200) context.stroke() context.move_to(0,mi) context.line_to(200,mi) context.stroke() # save svg file context = None surface.finish()
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment