onScale and Canvas - how to adjust origin point af

2019-03-29 08:54发布

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 screenshot

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条回答
够拽才男人
2楼-- · 2019-03-29 09:41

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

查看更多
登录 后发表回答