diff --git a/kivy/core/window/__init__.py b/kivy/core/window/__init__.py index 556652df46..3cabeee06f 100644 --- a/kivy/core/window/__init__.py +++ b/kivy/core/window/__init__.py @@ -1388,6 +1388,19 @@ def to_widget(self, x, y, initial=True, relative=False): def to_window(self, x, y, initial=True, relative=False): return (x, y) + def to_normalized_pos(self, x, y): + '''Transforms absolute coordinates to normalized (0-1) coordinates + using :attr:`system_size`. + + .. versionadded:: 2.1.0 + ''' + x_max = self.system_size[0] - 1.0 + y_max = self.system_size[1] - 1.0 + return ( + x / x_max if x_max > 0 else 0.0, + y / y_max if y_max > 0 else 0.0 + ) + def _apply_transform(self, m): return m diff --git a/kivy/tests/test_window_base.py b/kivy/tests/test_window_base.py new file mode 100644 index 0000000000..d99ebdce87 --- /dev/null +++ b/kivy/tests/test_window_base.py @@ -0,0 +1,20 @@ +from itertools import product + +from kivy.tests import GraphicUnitTest + + +class WindowBaseTest(GraphicUnitTest): + + def test_to_normalized_pos(self): + win = self.Window + old_system_size = win.system_size[:] + win.system_size = w, h = type(old_system_size)((320, 240)) + try: + for x, y in product([0, 319, 50, 51], [0, 239, 50, 51]): + expected_sx = x / (w - 1.0) + expected_sy = y / (h - 1.0) + result_sx, result_sy = win.to_normalized_pos(x, y) + assert result_sx == expected_sx + assert result_sy == expected_sy + finally: + win.system_size = old_system_size