Skip to content

Instantly share code, notes, and snippets.

@inclement
Created February 24, 2019 22:54
Show Gist options
  • Select an option

  • Save inclement/4059dd23ee9b0887517b93885d9817b1 to your computer and use it in GitHub Desktop.

Select an option

Save inclement/4059dd23ee9b0887517b93885d9817b1 to your computer and use it in GitHub Desktop.
from kivy.lang import Builder
from kivy.uix.anchorlayout import AnchorLayout
from kivy.base import runTouchApp
class AspectRatioEnforcer(AnchorLayout):
def on_size(self, instance, size):
self.resize_child()
def resize_child(self):
if not self.children:
# No child widget is present to resize
return
child = self.children[0]
aspect_ratio = 16 / 9.
if self.width > aspect_ratio * self.height:
child_height = self.height
child_width = aspect_ratio * child_height
else:
child_width = self.width
child_height = child_width / aspect_ratio
child.size_hint = (None, None)
child.width = child_width
child.height = child_height
if __name__ == "__main__":
runTouchApp(Builder.load_string("""
AspectRatioEnforcer:
Widget:
canvas:
Color:
rgba: 1, 0, 0, 1
Rectangle:
pos: self.pos
size: self.size
"""))
@brokenshield
Copy link
Copy Markdown

Thank you! That's very helpful. Is there place I can appropriately add in:

        anchor_x: 'center'
        anchor_y: 'center'

To get the entire AspectRatioEnforcer(AnchorLayout) to center itself?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment