简体   繁体   中英

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

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):

Nexus截图

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.

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM