[英]How to draw a GdkPixbuf using GTK3 and PyGObject
我有一个小应用程序,它使用DrawingArea
使用PyGObject
和GTK3
绘制一个简单的地图。
我使用加载Pixbuf
from gi.repository import Gtk, GdkPixbuf
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size("logo.png", 25, 25)
然后尝试在DrawingArea
的绘图事件信号中绘制它
def draw(self, widget, context):
window = widget.get_window()
ctx = window.cairo_create()
ctx.set_source_pixbuf(pixbuf, 0, 0)
但我收到错误信息
"AttributeError: 'cairo.Context' object has no attribute 'set_source_pixbuf'"
如果我正确地阅读Gtk2到Gtk3迁移指南 ,这应该可行。 我究竟做错了什么?
新的绘制信号使用已经将cairo上下文作为参数传递的回调,你不需要像在PyGtk中那样做像window = widget.get_window()
这样的东西来获取cairo上下文,同时参加expos -event信号。 在PYGObject中更简单:
import cairo
class Foo(object):
def __init__(self):
(...)
self.image = cairo.ImageSurface.create_from_png('logo.png')
(...)
def draw(self, widget, context):
if self.image is not None:
context.set_source_surface(self.image, 0.0, 0.0)
context.paint()
else:
print('Invalid image')
return False
也就是说,如果您不需要PixBuf,但如果您需要其它的东西,您有几个选择:
如果你选择了糟糕的第二个选项,那么如何:
import Image
import array
from gi.repository import Gtk, GdkPixbuf
width = 25
height = 25
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size('logo.png', width, height)
pil_image = Image.fromstring('RGBA', (width, height), pixbuf.get_pixels())
byte_array = array.array('B', pil_image.tostring())
cairo_surface = cairo.ImageSurface.create_for_data(byte_array, cairo.FORMAT_ARGB32, width, height, width * 4)
请注意, create_for_data() 尚不适用于Python3 , 仅适用于Python2 。
如果这是你想要实现的,请查看我在PyGObject中如何使用双缓冲区的答案: 在PyGobject中绘图(python3)
亲切的问候
以下似乎做了这个工作:
def draw(self, widget, context):
Gdk.cairo_set_source_pixbuf(context, self.pixbuf, 0, 0)
context.paint()
一个问题仍然存在:这是首选的做事方式吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.