如何在缩放后在Android ImageView上绘图?

时间:2016-03-23 15:49:00

标签: java android canvas imageview ontouch

我有一个ImageView,我想用两根手指进行缩放/拖动,然后用一根手指在上面画画,但是在缩放ImageView后,位图坐标和ImageView坐标不匹配,为了解决这个我提供的OnTouch就像这个:

@Override
public boolean onTouch(View v, MotionEvent event) {
    ImageView view = (ImageView) v;
    final int NONE = 0;
    final int DRAW = 1;
    final int PINCH = 2;
    float x,y;

    switch (event.getAction() & MotionEvent.ACTION_MASK){
        case MotionEvent.ACTION_DOWN:
            drawStartX = event.getX();
            drawStartY = event.getY();
            imageMode = DRAW;
            break;

        case MotionEvent.ACTION_POINTER_DOWN:
            //drag
            savedMatrix.set(matrix);
            start.set(event.getX(), event.getY());

            x = event.getX(0) - event.getX(1);
            y = event.getY(0) - event.getY(1);
            oldDistance = (float) Math.sqrt(x * x + y * y);
            if (oldDistance > 5f) {
                savedMatrix.set(matrix);
                x = event.getX(0) + event.getX(1);
                y = event.getY(0) + event.getY(1);
                mid.set(x / 2, y / 2);
                imageMode = PINCH;
            }
            break;

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

        case MotionEvent.ACTION_MOVE:
            if (imageMode == DRAW) {
                float drawEndX = event.getX();
                float drawEndY = event.getY();
                drawTest(drawStartX/bitmapScale - xTranslate, drawStartY/bitmapScale- yTranslate,drawEndX/bitmapScale - xTranslate,drawEndY/bitmapScale - yTranslate,0);
            } else if (imageMode == PINCH) {
                x = event.getX(0) - event.getX(1);
                y = event.getY(0) - event.getY(1);
                float newDistance = (float) Math.sqrt(x * x + y * y);
                matrix.set(savedMatrix);
                if(newDistance > 5f) {
                    //drag

                    float dx = event.getX() - start.x;
                    float dy = event.getY() - start.y;
                    matrix.postTranslate(dx, dy);

                    //zoom
                    float scale = (newDistance / oldDistance);
                    matrix.postScale(scale, scale);

                }
                //get matrix
                float[] mat = new float[9];
                matrix.getValues(mat);
                bitmapScale = mat[0];
                xTranslate = mat[2];
                yTranslate = mat[5];

            }
            break;
    }
    view.setImageMatrix(matrix);
    return true;
}

drawTest只是一个划线的空白。

pic

在缩放图片之前我在imageview上拖动手指并在精确位置绘制线条,但在缩放后我拖动到同一位置但结果不正确

但它无法正常工作。我该如何解决?

0 个答案:

没有答案