SoFunction
Updated on 2025-03-02

Analyze the implementation method of multi-touch in Android development


// Import
public class ImageViewerActivity extends Activity implements OnTouchListener { 

    private ImageView mImageView; 

    private Matrix matrix = new Matrix(); 
    private Matrix savedMatrix = new Matrix(); 

    private static final int NONE = 0; 
    private static final int DRAG = 1; 
    private static final int ZOOM = 2; 
    private int mode = NONE; 

// The point of the first finger pressed
    private PointF startPoint = new PointF(); 
// The midpoint of the touch point of the two pressed fingers
    private PointF midPoint = new PointF(); 
// The distance between the touch point pressed by the initial two fingers
    private float oriDis = 1f; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        (savedInstanceState); 
        (); 
        mImageView = (ImageView) (); 
        (this); 
    } 

    @Override 
    public boolean onTouch(View v, MotionEvent event) { 
        ImageView view = (ImageView) v; 

// Perform and operation is to judge multi-touch
        switch (() & MotionEvent.ACTION_MASK) { 
        case MotionEvent.ACTION_DOWN: 
// The first finger press event
            (()); 
            (matrix); 
            ((), ()); 
            mode = DRAG; 
            break; 
        case MotionEvent.ACTION_POINTER_DOWN: 
// The second finger pressing event
            oriDis = distance(event); 
            if (oriDis > 10f) { 
                (matrix); 
                midPoint = middle(event); 
                mode = ZOOM; 
            } 
            break; 
        case MotionEvent.ACTION_UP: 
        case MotionEvent.ACTION_POINTER_UP: 
// Finger release incident
            mode = NONE; 
            break; 
        case MotionEvent.ACTION_MOVE: 
// Finger sliding event
            if (mode == DRAG) { 
// It's a finger drag
                (savedMatrix); 
                (() - , () 
                        - ); 
            } else if (mode == ZOOM) { 
// Slide two fingers
                float newDist = distance(event); 
                if (newDist > 10f) { 
                    (savedMatrix); 
                    float scale = newDist / oriDis; 
                    (scale, scale, , ); 
                } 
            } 
            break; 
        } 

// Set up the Matrix of ImageView
        (matrix); 
        return true; 
    } 

// Calculate the distance between two touch points
    private float distance(MotionEvent event) { 
        float x = (0) - (1); 
        float y = (0) - (1); 
        return (x * x + y * y); 
    } 

// Calculate the midpoint of two touch points
    private PointF middle(MotionEvent event) { 
        float x = (0) + (1); 
        float y = (0) + (1); 
        return new PointF(x / 2, y / 2); 
    }