过去我在学习 Cairo 时拍过一些照片,但总是继续支持其他一些图形库。我的问题是我找不到一个很好的教程来为我的表面提供一个简单的显示。我总是在 GTK 或 QT 文档中挖掘与我想做的事情无关的事情。我想学习 Cairo,而不是大规模的 OO 架构。
什么是一个简单的框架包装器,可以给我一个带有开罗 Canvas 的跨平台窗口进行绘制?
最佳答案
我几乎在任何涉及绘画的事情上都使用过 cairo。我在一家医疗软件公司工作,所以我制作了科学数据可视化和其他东西的原型(prototype)。
我通常有三种方式来展示我的图纸:
show()
直接在屏幕上显示的 PNG 图像方法; 一个从 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()
或者,如果您不想处理 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')
关于cairo - 开始使用 cairo 的最快方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5575959/