使用(Py)GTK调整大小时自动缩放图像
发布时间:2021-01-11 08:18:19 所属栏目:Python 来源:互联网
导读:我在一个可调整大小的窗口中有一个Gtk Image小部件,并且存储了我想要填充GtkImage的图像的参考GdkPixBuf. 我可以使用此方法缩放GdkPixBuf以填充GtkImage小部件: def update_image(self, widget=None, data=None): # Get the size of the source pixmap src_w
|
我在一个可调整大小的窗口中有一个Gtk Image小部件,并且存储了我想要填充GtkImage的图像的参考GdkPixBuf. 我可以使用此方法缩放GdkPixBuf以填充GtkImage小部件: def update_image(self,widget=None,data=None):
# Get the size of the source pixmap
src_width,src_height = self.current_image.get_width(),self.current_image.get_height()
# Get the size of the widget area
widget = self.builder.get_object('image')
allocation = widget.get_allocation()
dst_width,dst_height = allocation.width,allocation.height
# Scale preserving ratio
scale = min(float(dst_width)/src_width,float(dst_height)/src_height)
new_width = int(scale*src_width)
new_height = int(scale*src_height)
pixbuf = self.current_image.scale_simple(new_width,new_height,gtk.gdk.INTERP_BILINEAR)
# Put the generated pixbuf in the GtkImage widget
widget.set_from_pixbuf(pixbuf)
当我手动调用update_image时,它按预期工作.现在我希望在调整GtkImage小部件时自动进行缩放.我带来的最佳解决方案是将update_image方法绑定到窗口的configure-event GTK事件.在窗口的每次尺寸改变之后,图像确实被适当地缩放.但是我对此解决方案有两个问题: >我只能让窗户更大.一旦图像被放大,GTK将不会让我调整窗口的大小,因为窗口不能小于其窗口小部件.我明白为什么它会这样,但我不知道如何改变这种行为. 我很抱歉这个小问题的长期解释,我希望你能帮助我. 解决方法我相信你可以使用小部件的 expose-event信号进行图像缩放.另外,将图像添加到可滚动容器中可以解决窗口调整大小的问题.请检查下面的示例是否适合您.import gtk
class ScaleImage:
def __init__(self):
self.temp_height = 0
self.temp_width = 0
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
image = gtk.Image()
image.set_from_file('/home/my_test_image.jpg')
self.pixbuf = image.get_pixbuf()
image.connect('expose-event',self.on_image_resize,window)
box = gtk.ScrolledWindow()
box.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)
box.add(image)
window.add(box)
window.set_size_request(300,300)
window.show_all()
def on_image_resize(self,widget,event,window):
allocation = widget.get_allocation()
if self.temp_height != allocation.height or self.temp_width != allocation.width:
self.temp_height = allocation.height
self.temp_width = allocation.width
pixbuf = self.pixbuf.scale_simple(allocation.width,allocation.height,gtk.gdk.INTERP_BILINEAR)
widget.set_from_pixbuf(pixbuf)
def close_application(self,data=None):
gtk.main_quit()
return False
if __name__ == "__main__":
ScaleImage()
gtk.main()
希望这有帮助,问候 (编辑:哈尔滨站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
