Monday, June 9, 2014

20. Touch Coordinates

on_touch_down is fired when a touch, on mobile, or a mouse click, on desktop, is detected. on_size is called whenever the size of the window changes, as well as at startup.




We use BoxLayout as base for the root class. We import graphics classes since drawings will be done in the Python file. The only function of on_touch_down, here, is to print the coordinates that it receives.




The on_size function is called whenever the size property changes. In the first half of this function, the lists px and py are created. They hold the coordinates for 9 horizontal lines and 9 vertical lines.




First the canvas is cleared so the old instructions do not effect the screen. Then, we create a red background color as well as 18 blue lines, half horizontal and half vertical.




The app class is created and run.


# ex20.py

from kivy.uix.boxlayout import BoxLayout
from kivy.app import App
from kivy.graphics import Color, Line, Rectangle

class Ex20(BoxLayout):
    def on_touch_down(self, touch):
        print("pos: {}\nspos: {}\n".format(touch.pos,touch.spos))
    def on_size(self,*args):
        self.px = []
        self.py = []
        w = self.width
        h = self.height
        for r in range(1,10):
            rw = r / 10.0
            self.px.extend([rw*w,0,rw*w,h])
            self.py.extend([0,rw*h,w,rw*h])
        self.canvas.clear()
        with self.canvas:
            Color(1,0,0)
            Rectangle(size=self.size)
            Color(0,0,1)
            for i in range(9):
                Line(points=self.px[i*4:i*4+4],width=2)
                Line(points=self.py[i*4:i*4+4],width=2)
                
class Ex20App(App):
    def build(self):
        return Ex20()

if __name__=='__main__':
    Ex20App().run()



This is the result of the execution. Due to the lines, we create a grid and we can click at any point and see the Python console.




The Python console shows the results from the printouts in the on_touch_down function. The first three are due to clicks in the upper-right-corner, and the last three clicks are in the lower-left corner of the screen.




3 comments:

  1. I like the algorithm for the points of the lines, classy :D

    ReplyDelete
  2. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

    Python Training in electronic city

    ReplyDelete