Canvas - zooming in, shifting, and scaling on Android

前端 未结 5 994
广开言路
广开言路 2020-12-24 00:34

I\'m currently implementing a draw function on a webview image (the elephant below). I don\'t have a problem drawing on it but the zoom function does some funky stuff (2nd i

5条回答
  •  一个人的身影
    2020-12-24 01:25

    I have implemented this behaviour, but in a slightly different way. I used a matrix to handle all the zooming and scrolling (and rotation, in my case). It makes for neat code and works like clockwork. I don't know what is causing your funky behaviour, though.

    Store a Matrix and another path as class members:

    Matrix drawMatrix = new Matrix();
    Path transformedPath = new Path();
    

    Replace your onScale:

    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        Matrix transformationMatrix = new Matrix();
    
        //Zoom focus is where the fingers are centered, 
        transformationMatrix.postTranslate(-detector.getFocusX(), -detector.getFocusY());
    
        transformationMatrix.postScale(detector.getScaleFactor(), detector.getScaleFactor());
    
    /* Using getFocuShift allows for scrolling with two pointers down. Remove it to skip this functionality */
        transformationMatrix.postTranslate(detector.getFocusX() + detector.getFocusShiftX(), detector.getFocusY() + detector.getFocusShiftY());
    
        drawMatrix.postConcat(transformationMatrix);
        invalidate();
        return true;
    }
    

    in onDraw; skip saving the canvas, instead:

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    
        canvas.drawBitmap(canvasBitmap, drawMatrix, canvasPaint);
        transformedPath.rewind();
        transformedMatrix.addPath(drawPath);
        transformedPath.transform(drawMatrix, null);
        canvas.drawPath(transformedPath, drawPaint);
    }
    

    Happy coding!

提交回复
热议问题