Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wxpython: automatically resize a static image (staticbitmap) to fit into size

My wxPython project has a frame, with multiple nested sizers.

One of the sizers contains a wxStaticImage with a bitmap that is read from a file.

I need the image to resize (grow/shrink) every time the frame is resized, so it will fit it's sizer's boundaries.

(I think that) I know how to resize an image. What I don't know is how to:

  • how to get the image's container's width or height?
  • maybe i overlooked a property that does it auotmatically?

(for now, I don't mind the proportions)

Edit: Complete solution

  1. i understood wrong about wxStaticBitmapin.Size. it does NOT describe the size of the image (i.e. image resolution), but rather - wxStaticBitmapin.Size gives the sizer's slot dimentions, or in other words: the current widget's size.

    so with Mik's code i now how to fit into the slot.

  2. in addition to mike's solution: when using onSize event on a frame, don't forget to add event.skip(). otherwise the sizers will stop re-aligning. Altertanively, just use the image's onSize.

here's the complete event method:

def bitmap1_onSize(self, e=None):
    W, H = self.bitmap1.Size
    if W > H:
        NewW = W
        NewH = W * H / W
    else:
        NewH = H
        NewW = H * W / H
    img = wx.Image(self.frame_file_picker.Path, wx.BITMAP_TYPE_ANY)
    img = img.Scale(NewW,NewH)
    self.bitmap1.SetBitmap(wx.BitmapFromImage(img))
    e.Skip()
like image 628
Berry Tsakala Avatar asked Dec 04 '12 15:12

Berry Tsakala


1 Answers

You will need to catch EVT_SIZE or EVT_SIZING. You can check out this tutorial I wrote about creating an image viewer. It has some scaling code in it: http://www.blog.pythonlibrary.org/2010/03/26/creating-a-simple-photo-viewer-with-wxpython/

I would just take that scaling code and use it to update your image. You'll want to make sure you stop scaling your image up past its maximum size or you'll end up with a lot of pixelization though.

like image 121
Mike Driscoll Avatar answered Nov 03 '22 07:11

Mike Driscoll