Android:在自定义视图的onTouchListener中实现

时间:2017-03-06 10:43:13

标签: android canvas view imageview ontouchlistener

我使用一些功能创建自定义ImageView,我的问题是实现。现在视图具有拖动和缩放功能。 这是onTouchListener:

@Override
public boolean onTouchEvent(MotionEvent event) {
    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:
            oldDist = spacing(event);
            if (oldDist > 10f) {
                savedMatrix.set(matrix);
                midPoint(mid, event);
                mode = ZOOM;
            }
            break;
        case MotionEvent.ACTION_UP:
            float[] values = new float[9];
            matrix.getValues(values);
        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 newDist = spacing(event);
                if (newDist > 10f) {
                    matrix.set(savedMatrix);
                    float scale = newDist / oldDist;
                    //SOME CODE
                }
            }
            break;
    }
    invalidate();
    return true;
}

我想在侦听器中检测到fling并在弹出后平滑地转换矩阵。如果我的任务有一个可行的解决方案,我将非常感激。

1 个答案:

答案 0 :(得分:1)

你可以使用GestureDetector,

class MyGestureListener implements GestureDetector.OnGestureListener {

    @Override
    public boolean onFling(MotionEvent event1, MotionEvent event2,
                           float velocityX, float velocityY) {
        if (event1.getY() - event2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
            return true; 
        } else if (event2.getY() - event1.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
            return true; 
        }
        return true;
    }

    @Override
    public boolean onDown(MotionEvent event) {
        return true;
    }

    @Override
    public void onShowPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent motionEvent) {

    }
}

你的onTouch方法,

@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
    return new GestureDetectorCompat(getActivity(), new MyGestureListener()).onTouchEvent(motionEvent);
}