PyGTK: How do I make an image automatically scale to fit its parent widget?
You can use widget.get_allocation() to find out the size of the parent widget and pixbuf.scale_simple to scale the image, like this:
allocation = parent_widget.get_allocation()
desired_width = allocation.width
desired_height = allocation.height
pixbuf = gtk.gdk.pixbuf_new_from_file('your_image.png')
pixbuf = pixbuf.scale_simple(desired_width, desired_height, gtk.gdk.INTERP_BILINEAR)
image = gtk.image_new_from_pixbuf(pixbuf)
If you want the image to scale each time the window is resized, you'll have to put the code above (or something similar, to avoid loading the image from disk every time) in a function connected to the size_allocate signal of the parent widget. To avoid infinite loops, make sure that the image you put in the widget doesn't alter its size again.
References:
- How to resize an image (I think you already visited that)
- About the "resize" event
- Other link about resizing, in Stack Overflow
Here is an except that accomplishes this task on a drawing area:
self.spash_pixbuf = GdkPixbuf.Pixbuf.new_from_file('myfile.png')
...
def on_draw(self, widget, cairo_ct):
"""
draw
"""
self._cairo_ct = cairo_ct
self._width = widget.get_allocated_width()
self._height = widget.get_allocated_height()
self._draw_cover(self.spash_pixbuf)
def _draw_cover(self, pixbuf):
"""
Paint pixbuf to cover drawingarea.
"""
img_width = float(pixbuf.get_width())
img_height = float(pixbuf.get_height())
# Scale
width_ratio = self._width / img_width
height_ratio = self._height / img_height
scale_xy = max(height_ratio, width_ratio)
# Center
off_x = (self._width - round(img_width*scale_xy)) //2
off_y = (self._height - round(img_height*scale_xy)) //2
# Paint
self._cairo_ct.save()
self._cairo_ct.translate(off_x, off_y)
self._cairo_ct.scale(scale_xy, scale_xy)
Gdk.cairo_set_source_pixbuf(self._cairo_ct, pixbuf, 0, 0)
self._cairo_ct.paint()
self._cairo_ct.restore()