开始使用cairo的最快捷方式

Eli*_*Eli 6 cairo

我过去在学习开罗时已经过了一些镜头,但总是转向其他一些图形库.我的问题是我找不到一个很好的教程,可以为我的表面提供一个简单的显示.我总是最终通过GTK或QT文档挖掘与我想做的事情无关的事情.我想学习开罗,而不是大规模的OO架构.

什么是裸骨包装,给我一个带有开罗画布的跨平台窗口?

hel*_*ker 10

我几乎把任何涉及绘画的东西都用过cairo.我在一家医疗软件公司工作,所以我将科学数据可视化和其他东西原型化.

我通常有三种方式来展示我的图纸:

  1. 使用Python脚本和GTK创建的GTK绘图区域;
  2. 使用Python Image Library show()方法直接在屏幕上显示PNG图像;
  3. PNG图像也通过Python Image Library保存到磁盘.

从cairographics示例派生的简单脚本,实际上我用作任何新项目的模板,是:

import gtk

class Canvas(gtk.DrawingArea):
    def __init__(self):
        super(Canvas, self).__init__()
        self.connect("expose_event", self.expose)
        self.set_size_request(800,500)

    def expose(self, widget, event):
        cr = widget.window.cairo_create()
        rect = self.get_allocation()

        # you can use w and h to calculate relative positions which
        # also change dynamically if window gets resized
        w = rect.width
        h = rect.height

        # here is the part where you actually draw
        cr.move_to(0,0)
        cr.line_to(w/2, h/2)
        cr.stroke()

window = gtk.Window()
canvas = Canvas()
window.add(canvas)
window.set_position(gtk.WIN_POS_CENTER)
window.show_all()
gtk.main()
Run Code Online (Sandbox Code Playgroud)

或者,如果您不想处理GUI工具包,可以在屏幕上创建和显示图像,并可选择将其保存到文件中:

import cairo, Image

width = 800
height = 600

surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
cr = cairo.Context(surface)

# optional conversion from screen to cartesian coordinates:
cr.translate(0, height)
cr.scale(1, -1)

# something very similar to Japanese flag:
cr.set_source_rgb(1,1,1)
cr.rectangle(0, 0, width, height)
cr.fill()
cr.arc(width/2, height/2, 150, 0, 6.28)
cr.set_source_rgb(1,0,0)
cr.fill()

im = Image.frombuffer("RGBA",
                       (width, height),
                       surface.get_data(),
                       "raw",
                       "BGRA",
                       0,1) # don't ask me what these are!
im.show()
# im.save('filename', 'png')
Run Code Online (Sandbox Code Playgroud)