Home » How To » How to resize a Gdk.Pixbuf to the size of a Gtk.Image visible area

How to resize a Gdk.Pixbuf to the size of a Gtk.Image visible area

I wrote a simple image viewer that will load a photo image into a Gtk.Image widget using a Gdk.Pixbuf.  I then added a tool bar with four clickable icons.  Zoom out, zoom in, fit to window and original size.

All but the fit to window worked well.  When I pulled the width and height from image1.GetSizeRequest(out width, out height), width & height were returned as -1.  Not helpful.  Google didn’t give me many clues either 🙁

What I needed was something that would provide the visible area of the Gdk.Image widget:

In order to get the visible area, we need to:

  • upcast Gtk.Image to a Gtk.GdkWindow
  • retrieve a Gdk.Region from the VisibleRegion method
  • retrieve the first Gdk.Rectangle from the array returned from the visibleRegion.GetRectangles method
  • extract the Height and Width from the Gdk.Rectangle

Now that we have the height and the width of the visible area of the Gtk.Image widget, we need to scale the image (Gdk.Pixbuf) while keeping the aspect. Assigning the image to the Gtk.Image widget will automatically redraw itself.

protected virtual void zoomToWindow (object sender, System.EventArgs e)
{
   if (image1.Pixbuf != null) {
     int new_width, new_height;
     int height = image1.Pixbuf.Height;
     int width = image1.Pixbuf.Width;

     Gdk.Region visibleRegion = image1.GdkWindow.VisibleRegion;
     Gdk.Rectangle rectangle = visibleRegion.GetRectangles()[0];
     new_height = rectangle.Height;
     new_width = rectangle.Width;
     scaleImage(height, width, ref new_height, ref new_width, 0);
     image1.Pixbuf = pictureBuf.ScaleSimple(new_width, new_height, Gdk.InterpType.Bilinear);
   }
}

There we go 🙂
While the code above is C#, the same principle goes for any language that uses Gtk.

Share Button

Comments

  1. DaMaD says:

    Thank you, that is what I was searching for 🙂

  2. Gerald says:

    Hi!

    To determine the size of a widget, you can call its get_allocation method. In python, it would look like this:

    allocated_size = wiget.get_allocation()
    width_of_widget = allocated_size.width
    height_of_widget = allocated_size.height

    Seems easier to me than your method and yields the same results AFAIK. However, I don’t know much, so maybe your way has an advantage to it I don’t recognize.

    Regards,
    Gerald

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*

Facebook login by WP-FB-AutoConnect