Created
October 28, 2014 04:17
-
-
Save vijinho/5bad31a16beedb9e02c8 to your computer and use it in GitHub Desktop.
Python Kivy: Rescale an image to fit a given viewport size without losing aspect ratio
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyImage(Image): | |
def __init__(self, **kwargs): | |
super(MyImage, self).__init__() | |
def texture_width(self): | |
return self.texture.size[0] | |
def texture_height(self): | |
return self.texture.size[1] | |
def rescale(self, width, height): | |
""" | |
Resize the image to fit the given dimensions, zooming in or out if | |
needed without losing the aspect ratio | |
:param width: target width | |
:param height: target height | |
:return: new dimensions as a tuple (width, height) | |
""" | |
ratio = 0.0 | |
new_width = 0.0 | |
new_height = 0.0 | |
target_width = float(width) | |
target_height = float(height) | |
image_width = float(self.texture_width()) | |
image_height = float(self.texture_height()) | |
ratio = target_width / image_width | |
new_width = image_width * ratio | |
new_height = image_height * ratio | |
if (new_height < target_height): | |
ratio = target_height / new_height | |
new_height *= ratio | |
new_width *= ratio | |
if new_width > 0 and new_height > 0: | |
self.width = new_width | |
self.height = new_height | |
return (new_width, new_height) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment