Android Tutorial Android multitouch tutorial

Using Agraham's Gestures library we can handle multitouch events.

This is an example of a simple drawing application that supports multitouch:

multitouch_1.png


As you can see in the above screenshot, each finger draws with a different color and it also displays the current id and position of each touch.

In order to support multitouch a Gestures object is used to add a listener to a specific view.
The listener is responsible for raising an event with every movement or change in the multitouch state.

Inside this event we are handling the gesture. Each touch gets a pointer id during a gesture. The pointer id is assigned when a finger touches the screen and is released when the same finger leaves the screen.

I find it useful to maintain a Map with the pointer ids as the keys and the the extra data that you want to assign to each touch as values.
In our example we store the color and the previous position as the value.

Maintaining the map is done with the following code:
B4X:
Sub GesturesTouch(View As Object, PointerID As Int, Action As Int, X As Float, Y As Float) As Boolean
    Dim p As Point
    Select Action
        Case g.ACTION_DOWN, g.ACTION_POINTER_DOWN
            'New Point is assigned to the new touch
            p.Id = PointerID
            p.Color = Colors.RGB(Rnd(0, 255), Rnd(0, 255), Rnd(0, 255))
            TouchMap.Put(PointerID, p)
        Case g.ACTION_POINTER_UP
            TouchMap.Remove(PointerId)
        Case g.ACTION_UP
            TouchMap.Clear
    End Select
  ...
The Point type is declared in Sub Globals:
B4X:
Type Point(Id As Int, prevX As Int, prevY As Int, Color As Int)
The result is that TouchMap holds information about the active touches.
Now all that is left to do is to iterate over the TouchMap values and connect the previous coordinates with the new ones and then update the previous coordinates.
The new coordinates are retrieved by calling g.GetX/Y with the pointer id.
B4X:
    Dim px, py As Int
    For i = 0 To TouchMap.Size - 1
        p = TouchMap.GetValueAt(i)
        px = g.GetX(p.id) 'Get the current coordinates of this touch
        py = g.GetY(p.id)
        Dim s As String
        s = p.Id & ": " & px & " x " & py
        Canvas.DrawText(s, 10dip, 20dip + i * RowHeight, Typeface.DEFAULT, TextSize, p.Color, "LEFT")
        If p.prevX > 0 AND p.prevY > 0 Then
            Canvas.DrawLine(p.prevX, p.prevY, px, py, p.Color, 5dip)
        End If
        p.prevX = px
        p.prevY = py
    Next
    bgd.Invalidate
p.prevX and p.prevY will equal 0 when the touch starts. In this case we do not draw anything.

The gesture sub should return true or otherwise no more events will be raised for this gesture.
 

Attachments

  • MultitouchExample.zip
    7.3 KB · Views: 733
Last edited:
Top