1

我编写了一个使用拖动和缩放的 android 应用程序。但是当我编程Touch课时MotionEvent.ACTION_DOWNMotionEvent.ACTION_POINTER_DOWNMotionEvent.ACTION_MOVE没有工作。如何修复我的代码?

触摸类:

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

private static final float MAX_ZOOM = 3f;
private static final float MIN_ZOOM = 3f;

public boolean onTouch(View view, MotionEvent event) {
    int mode = NONE;
    float oldDistance = 1f;

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

    PointF start = new PointF();
    PointF mid = new PointF();

    ImageView imageView = (ImageView)view;

    switch(event.getAction() & MotionEvent.ACTION_MASK) {

        case MotionEvent.ACTION_DOWN:
            savedMatrix.set(matrix);
            start.set(event.getX(), event.getY());
            mode = DRAG;
            break;

        case MotionEvent.ACTION_POINTER_DOWN:
            oldDistance = spacing(event);
            if(oldDistance > 10f) {
                savedMatrix.set(matrix);
                midPoint(mid, event);
                mode = ZOOM;
            }
            break;

        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_POINTER_UP:
            mode = NONE;
            break;

        case MotionEvent.ACTION_MOVE:
            if(mode == DRAG) {
                matrix.set(savedMatrix);
                matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);
            }
            else if(mode == ZOOM) {
                float newDistance = spacing(event);
                if(newDistance > 10f) {
                    matrix.set(savedMatrix);
                    float scale = newDistance / oldDistance;
                    float[] values = new float[9];
                    matrix.getValues(values);
                    float currentScale = values[Matrix.MSCALE_X];
                    if(scale * currentScale > MAX_ZOOM) 
                        scale = MAX_ZOOM / currentScale;
                    else if (scale * currentScale < MIN_ZOOM) 
                        scale = MIN_ZOOM / currentScale;
                    matrix.postScale(scale, scale, mid.x, mid.y);
                }
            }
            break;
    }
    imageView.setImageMatrix(matrix);
    return true;
}

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);
 }

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);
 }
4

1 回答 1

0

有必要使用 switch case 语句吗?您可能更容易阅读,但是当我这样做时>>

    if (event.getAction() == MotionEvent.ACTION_UP){

    } else if (event.getAction() == MotionEvent.ACTION_DOWN) {

    } else if (event.getAction() == MotionEvent.ACTION_MOVE) {

    }

它工作得很好。此外,您应该在 case 语句中添加日志调用,以了解您的 onTouch 是否被调用,以及它通过哪些情况,哪些情况不通过。您还可以记录掩码和事件代码传入的值吗?这些都会有所帮助。

于 2012-08-18T00:00:55.270 回答