what is the best way to draw a rounded rectangle in a pygtk application
+1
A:
#!/usr/bin/env python
import gtk
def rounded_rectangle(cr, x, y, w, h, r=20):
# This is just one of the samples from
# http://www.cairographics.org/cookbook/roundedrectangles/
# A****BQ
# H C
# * *
# G D
# F****E
cr.move_to(x+r,y) # Move to A
cr.line_to(x+w-r,y) # Straight line to B
cr.curve_to(x+w,y,x+w,y,x+w,y+r) # Curve to C, Control points are both at Q
cr.line_to(x+w,y+h-r) # Move to D
cr.curve_to(x+w,y+h,x+w,y+h,x+w-r,y+h) # Curve to E
cr.line_to(x+r,y+h) # Line to F
cr.curve_to(x,y+h,x,y+h,x,y+h-r) # Curve to G
cr.line_to(x,y+r) # Line to H
cr.curve_to(x,y,x,y,x+r,y) # Curve to A
def expose(canvas, event):
# Create cairo context
cr = canvas.window.cairo_create()
# Restrict drawing to the exposed area, so that
# no unnecessary drawing is done
cr.rectangle(event.area.x, event.area.y,
event.area.width, event.area.height)
cr.clip()
rounded_rectangle(cr, 100, 100, 100, 100)
cr.set_line_width(4.0)
cr.set_source_rgb(1.0, 0.0, 0.0)
cr.stroke_preserve()
cr.set_source_rgb(1.0, 0.5, 0.5)
cr.fill()
# Construct window
window = gtk.Window()
canvas = gtk.DrawingArea()
canvas.set_size_request(300, 300)
canvas.connect('expose-event', expose)
window.connect('delete-event', gtk.main_quit)
window.add(canvas)
window.show_all()
gtk.main()
ptomato
2010-03-07 11:29:37
If you are going to paint this several times (lets say... an animation), you should use double buffer to avoid flicks, check this code on my blog: http://tinyurl.com/38vpgtw
markuz
2010-05-07 05:56:42