Skip to content
Advertisement

How to make Canvas vertex instructions relative to a widget in Kivy

I just started learning Kivy and I was trying to understand how the Canvas instructions are affected on resizing of the window of the kivyApp.

In the Kivy documentation it is mentioned that –

JavaScript

The example which follows, shows how to bind the size and position of a Rectangle instruction to the size and position of the widget in which it is being drawn. Therefore the size and the position changes proportionally when the window is resized.

But, how can I do the same for somthing like a Bezier instruction, which uses points.

I have a custom widget HangManFig1 which extend the Widget class, which is defined in KVlang like this:

JavaScript

I use this widget in a Screen, in the following manner:

JavaScript

KivyApp in full screen

When I am resizing the window, I see that although the Buttons are being positioned correctly, but not HangManFig1.

Enter image description here

Is there a way, in which I can bind the size of this widget to that of the Parent Widget so that it is positioned correctly even when the Window size changes?

Advertisement

Answer

While you used RelativeLayout to make the coordinates of your instructions relative to the position of your widget, it doesn’t do anything regarding its size.

As you hardcoded all the positions by numeric values, you’ll need a way to scale these values relative to the size of your widget, and you have to consider what you want to happen regarding the width of your lines in this situation, should it grow relative to the size of the widget as well? linearly? Something else? Depending on what you want various possibility exist.

The easiest starting point, IMHO, would be to use a Scale instruction, to set all the canvas instructions relative to the size of your widget, over the size you used to design your current hangman.

JavaScript

If that’s not enough for you, because you want to keep the width of the line constant for example, you could either not do it with a Scale instruction, but instead have a function that takes the size of your widget and a set of coordinates as input, and returns the value relative to that size:

JavaScript

This function could be used like this.

JavaScript

And if you want something more sophisticated, like preserving the aspect ratio of your hangman, while staying in the boundaries of your size, you could adjust accordingly to something like:

JavaScript
Advertisement