onScale and Canvas - how to adjust origin point after zooming image?

淺唱寂寞╮ 提交于 2019-12-21 05:12:05

问题


I have a very simple test app with a custom component MyView.java - which displays a scrollable and scalable image (representing a board in a Scrabble-like word game):

1) In my scale listener I adjust the scale factor:

public boolean onScale(ScaleGestureDetector detector) {
    mScale *= detector.getScaleFactor();

    // XXX how to adjust mOffsetX and mOffsetY ? XXX

    constrainZoom();
    constrainOffsets();
    invalidate();
    return true;
}

2) And then in the drawing method of my custom component I apply the translation and scale factor:

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.translate(mOffsetX, mOffsetY);
    canvas.scale(mScale, mScale);
    gameBoard.setBounds(
        0, 
        0, 
        gameBoard.getIntrinsicWidth(),
        gameBoard.getIntrinsicHeight()
    );
    gameBoard.draw(canvas);  
}

Unfortunately, there seems to be a small bug when scaling with pinch gesture -

I can see, that the scale and boundaries are of correct size after zooming, but the offset of the image is not.

The problem get worse, when the focus point of the pinch gesture is far from 0, 0 point of the screen.

It is a bit difficult to describe the problem in words, but when you check out my test project from GitHub you will see it immediately (and you can always double tap to reset the offset and the scale).

This is probably a common problem with a standard way to solve it, but I haven't been able to find it yet.

The board image is CC BY-SA by Denelson83 and the code is based on the How-to support the fling gesture with a bounce effect blog.


回答1:


You are moving the canvas twice: first with translate, then with scale(sx,sy,px,py);.

You could combine your focuses to your offsets in your onScale and then use scale(sx,sy).



来源:https://stackoverflow.com/questions/26609739/onscale-and-canvas-how-to-adjust-origin-point-after-zooming-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!