How to auto resize images according to window size

Ok, that accepted stackoverflow answer is the worst thing I’ve ever seen in my life.

The actual thing you need to do is to just write your own widget.

  1. Subclass GtkWidget (or GtkDrawingArea I guess)
  2. In your widget subclass, have some setter for the image. Preferrable always work with cairo_surface_t as that is what is being drawn in the end anyway. If you save your images as GdkPixbuf or anything else, convert them to a cairo_surface_t
  3. Override ::draw
    3.5) There is a function called gdk_cairo_set_source_pixbuf() that people love to use here. Instead of working with a cairo_surface_t, it takes a GdkPixbuf which is more common. You can do that too, but the function does nothing but convert the pixbuf to a surface and then set that as the source surface. In other words, it’s slow.
  4. In ::draw, you can use simple cairo commands to draw your surface, and scale it using cairo_scale(). Get the size of the widget, the size of the surace, do a bit of math and voila.

DO NOT connect to size-allocate and resize a pixbuf or some garbage. That’s just hilarious.

3 Likes