使用ScaleGestureDetector时,在放大太大后无法缩小

时间:2014-12-18 07:40:14

标签: java android

我使用了ScaleGestureDectector类的自定义视图。我的问题是当我以4.5倍放大时,我的自定义布局无法缩小。

这是我的代码:

private class ScaleGestureListener
            extends ScaleGestureDetector.SimpleOnScaleGestureListener {

    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        float scaleFactor = mScaleFactor * detector.getScaleFactor();

        mScaleFactor = scaleFactor;
        setScaleX(getScaleX() * mScaleFactor);
        setScaleY(getScaleY() * mScaleFactor);

        invalidate();
        return true;
    }

针对此问题的任何解决方案?我想放大我的布局至少4.5倍

1 个答案:

答案 0 :(得分:-1)

而不是:

float scaleFactor = mScaleFactor * detector.getScaleFactor();

这样做:

float scaleFactor = Math.max(4.5F, mScaleFactor * detector.getScaleFactor());

这可确保您的最小缩放比例因子为4.5

编辑:我误解了你的问题。看起来好像你不应该跟踪mScaleFactor。 API为您做了繁重的工作。 根据API,getScaleFactor() 返回the scaling factor from the previous scale event to the current event.

因此,当您在字段中跟踪mScaleFactor时,出现了问题:

// With these two lines, you're multiplying the variable mScaleFactor.
// Suppose that it was 3, and we're zooming out by 0.66666666
// Now, mScaleFactor is 2.
float scaleFactor = mScaleFactor * detector.getScaleFactor();
mScaleFactor = scaleFactor;

// Here, you're multiplying scaleX and scaleY by mScaleFactor (by 2. This effectively zooms in)
// You should only be multiplying them by 0.666666666 (effectively zooming out).
setScaleX(getScaleX() * mScaleFactor);
setScaleY(getScaleY() * mScaleFactor);

invalidate();
return true;

所以你的身体应该就是这样:

public boolean onScale(ScaleGestureDetector detector) {
    float scaleFactor = detector.getScaleFactor();

    setScaleX(getScaleX() * scaleFactor);
    setScaleY(getScaleY() * scaleFactor);

    invalidate();
    return true;
}