Commit ea2c7203 authored by Paul McCarthy's avatar Paul McCarthy 🚵
Browse files

ENH: ImagePanel has option to preserve aspect ratio

parent b6638fa6
...@@ -17,15 +17,21 @@ class ImagePanel(wx.Panel): ...@@ -17,15 +17,21 @@ class ImagePanel(wx.Panel):
:class:`wx.Image`. The image is scaled to the size of the panel. :class:`wx.Image`. The image is scaled to the size of the panel.
""" """
def __init__(self, parent, image=None): def __init__(self,
parent,
image=None,
preserveAspect=False):
"""Create an ``ImagePanel``. """Create an ``ImagePanel``.
If the ``image`` is not passed in here, it can be set later with the If the ``image`` is not passed in here, it can be set later with the
:meth:`SetImage` method. :meth:`SetImage` method.
:arg parent: The :mod:`wx` parent object. :arg parent: The :mod:`wx` parent object.
:arg image: The :class:`wx.Image` object to display. :arg image: The :class:`wx.Image` object to display.
:arg preserveAspect: Defaults to ``False``. If ``True``, the image
aspect ratio is preserved.
""" """
wx.Panel.__init__(self, parent) wx.Panel.__init__(self, parent)
...@@ -35,6 +41,8 @@ class ImagePanel(wx.Panel): ...@@ -35,6 +41,8 @@ class ImagePanel(wx.Panel):
self.SetImage(image) self.SetImage(image)
self.__preserveAspect = preserveAspect
def SetImage(self, image): def SetImage(self, image):
"""Set the image that is displayed on this ``ImagePanel``. """Set the image that is displayed on this ``ImagePanel``.
...@@ -70,11 +78,26 @@ class ImagePanel(wx.Panel): ...@@ -70,11 +78,26 @@ class ImagePanel(wx.Panel):
if not dc.IsOk(): if not dc.IsOk():
return return
width, height = dc.GetSize().Get() dwidth, dheight = dc.GetSize().Get()
if width == 0 or height == 0: if dwidth == 0 or dheight == 0:
return return
bitmap = self.__image.Scale(width, height).ConvertToBitmap() if self.__preserveAspect:
iwidth, iheight = self.__image.GetSize().Get()
iratio = float(iwidth) / iheight
dratio = float(dwidth) / dheight
# canvas is too wide - reduce
# the display image width
if dratio > iratio:
dwidth = dheight / iratio
# canvas is too tall - reduce
# the display image height
elif dratio < iratio:
dheight = dwidth * iratio
bitmap = self.__image.Scale(dwidth, dheight).ConvertToBitmap()
dc.DrawBitmap(bitmap, 0, 0, False) dc.DrawBitmap(bitmap, 0, 0, False)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment