How to use Multi-touch in Android 2: Part 6, Implementing the Pinch Zoom Gesture

Summary:Over the course of this series we've been working on a simple image viewer that lets you move and zoom a picture on the screen with touch gestures. This part wraps up the example with the code that implements multi-touch pinch zooming. All source code can be downloaded from the "Hello, Android" book web site.

Welcome to the last installment in the Android multi-touch series! The purpose of this series is to show you how to develop multi-touch programs for Android-based phones, tablets, and other devices. It was excerpted with permission from Hello, Android! (3rd edition), published by the Pragmatic Bookshelf.

Over the course of this series we've been working on a simple image viewer that lets you move and zoom a picture on the screen with touch gestures. This part wraps up the example with the code that implements multi-touch pinch zooming. All source code can be downloaded from the book web site.

The Android multi-touch series:
  1. Introducing Multi-Touch
  2. Building the Touch Example
  3. Understanding Touch Events
  4. Setting up for Image Transformation
  5. Implementing the Drag Gesture
  6. Implementing the Pinch Zoom Gesture

Implementing the Pinch Zoom Gesture

The pinch zoom gesture is similar to the drag gesture, except it starts when the second finger is pressed to the screen (ACTION_POINTER_DOWN).

From Touchv1/src/org/example/touch/

oldDist = spacing(event);
Log.d(TAG, "oldDist=" + oldDist);
if (oldDist > 10f) {
midPoint(mid, event);
mode = ZOOM;
Log.d(TAG, "mode=ZOOM" );

case MotionEvent.ACTION_MOVE: if (mode == DRAG) { // ... } else if (mode == ZOOM) { float newDist = spacing(event); Log.d(TAG, "newDist=" + newDist); if (newDist > 10f) { matrix.set(savedMatrix); float scale = newDist / oldDist; matrix.postScale(scale, scale, mid.x, mid.y); } } break;

When we get the down event for the second finger, we calculate and remember the distance between the two fingers. In my testing, Android would sometimes tell me (incorrectly) that there were two fingers pressed down in almost exactly the same position. So I added an check to ignore the event if the distance is smaller than some arbitrary number of pixels. If it’s bigger than that, we remember the current transformation matrix, calculate the midpoint of the two fingers, and start the zoom.

When a move event arrives while we’re in zoom mode, we calculate the distance between the fingers again. If it’s too small, the event is ignored, otherwise we restore the transformation matrix and scale the image around the midpoint.

The scale is simply the ratio of the new distance divided by the old distance. If the new distance is bigger (that is, the fingers have gotten further apart), then the scale will be greater than 1, making the image bigger. If it’s smaller (fingers closer together), then the scale will be less than one, making the image smaller. And of course if everything is the same, the scale is equal to 1 and the image is not changed.

Now let’s define the spacing( ) and midPoint( ) methods.

Distance Between Two Points

To find out how far apart two fingers are, we first construct a vector (x, y) which is the difference between the two points. Then we use the formula for Euclidean distance to calculate the spacing:

From Touchv1/src/org/example/touch/

private float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
The order of the points doesn’t matter because any negative signs will be lost when we square them. Note that all math is done using Java’s float type. While some Android devices may not have floating point hardware, we’re not doing this often enough to worry about its performance.

Midpoint of Two Points

Calculating a point in the middle of two points is even easier:

From Touchv1/src/org/example/touch/

private void midPoint(PointF point, MotionEvent event) {
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
All we do is take the average of their X and Y coordinates. To avoid garbage collections that can cause noticeable pauses in the application, we reuse an existing object to store the result rather than allocating and returning a new one each time.

Try running the program now on your phone. Drag the image with one finger, and zoom it by pinching two fingers in or out. For best results, don’t let your fingers get closer than an inch or so apart. Otherwise you’ll start to run into some of those bugs in the API I mentioned earlier.

Fast-Forward >>

In this chapter we learned how to use the multi-touch API to create a pinch zoom gesture. There’s a nice site called GestureWorks that describes a whole library of gestures that have been implemented on the Adobe Flash platform. If you’re willing to push the limits of Android’s quirky multi-touch support, then perhaps you can find ideas there for other gestures to implement in your Android programs.

Because multi-touch code uses new methods that didn’t exist before Android 2.0, if you try to run the Touch example on earlier versions it will fail with a “Force close” error. Luckily there are ways around this limitation (described later in the book - Ed). You can’t teach an old phone new tricks, but you can at least keep it from crashing.

In the next chapter we’ll investigate home screen extensions, including live wallpaper.

Copyright notice: This is an excerpt from Hello, Android 3rd edition, published by the Pragmatic Bookshelf. For more information or to purchase a paperback or PDF copy, please visit

Copyright © 2010 The Pragmatic Programmers, LLC. All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher.

Topics: Mobility, Google, Hardware


Ed Burnette has been hooked on computers ever since he laid eyes on a TRS-80 in the local Radio Shack. Since graduating from NC State University he has programmed everything from serial device drivers and debuggers to web servers. After a delightful break working on commercial video games, Ed reluctantly returned to business software. He... Full Bio

zdnet_core.socialButton.googleLabel Contact Disclosure

Kick off your day with ZDNet's daily email newsletter. It's the freshest tech news and opinion, served hot. Get it.

Related Stories

The best of ZDNet, delivered

You have been successfully signed up. To sign up for more newsletters or to manage your account, visit the Newsletter Subscription Center.
Subscription failed.