GTK+ 3: Vektorgrafiken mit Cairo
Hier zunächst nur ein einfaches Beispiel, wie man mit GtkDrawingArea und Cairo eine Vektorgrafik anzeigen lassen kann:
Code kopieren
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import cairo, math, gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class MainWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Zeichnen mit Cairo")
self.set_position(Gtk.WindowPosition.CENTER)
self.set_default_size(400, 400)
self.box01 = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, homogeneous=False, spacing=5)
self.add(self.box01)
self.button01 = Gtk.Button("Klick mich!")
self.button01.connect('clicked', self.on_button01_clicked)
self.box01.pack_start(self.button01, False, False, 0)
self.drawingarea01 = Gtk.DrawingArea()
self.drawingarea01.connect('draw', self.draw_something)
self.box01.pack_start(self.drawingarea01, True, True, 0)
self.show_all()
self.smile = True
def on_button01_clicked(self, widget):
if self.smile == True:
self.smile = False
else:
self.smile = True
self.drawingarea01.queue_draw() # Bewirkt ein Neuzeichnen der Grafik
def draw_something(self, widget, cr):
x = 200
y = 200
cr.set_source_rgb(1, 1, 0)
cr.arc(x, y, 100, 0, 2 * math.pi)
cr.fill_preserve()
cr.set_source_rgb(0, 0, 0)
cr.stroke()
cr.arc(x - 40, y - 30, 20, 0, 2 * math.pi)
cr.arc(x + 40, y - 30, 20, 0, 2 * math.pi)
cr.fill()
cr.set_line_width(10)
cr.set_line_cap(cairo.LINE_CAP_ROUND)
if self.smile == True:
cr.arc(x, y, 60, math.pi / 4, math.pi * 3 / 4)
else:
cr.arc(x, y + 100, 60, math.pi * 5 / 4, math.pi * 7 / 4)
cr.stroke()
win = MainWindow()
win.connect("delete-event", Gtk.main_quit)
Gtk.main()