3

我正在尝试在视图中同时使用 scalegesture 监听器和手势监听器。如果比例为 1,则一切正常,但如果比例设置为其他值,图像会抖动到一个新位置,然后平滑缩放。

我的部分代码如下所示:

public class SimpleView extends View {

Bitmap image;
ScaleGestureDetector scaleGesture;
GestureDetector gestures;
float touchX, touchY;
float horizontalOffset;
float verticalOffset;
float scale;

public SimpleView(Context context) {
    super(context);
    image = BitmapFactory.decodeResource(getResources(), R.drawable.some_image);
    scaleGesture = new ScaleGestureDetector(getContext(),
            new ScaleListener());
    gestures = new GestureDetector(getContext(), new GestureListener(),
            null, true);
    scale = 0.6f; //if this is set to  1.0f everything works perfectly,
            // else the imagetransports to a new position
            // and scales perfectly thereafter
}

@Override
protected void onDraw(Canvas canvas) {
    canvas.save();
    canvas.translate(horizontalOffset, verticalOffset);
    canvas.scale(scale, scale, touchX, touchY);
    canvas.drawBitmap(image, getMatrix(), new Paint);
    canvas.restore();
}

public class ScaleListener implements OnScaleGestureListener {
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        float oldScale = scale;
        scale *= detector.getScaleFactor();
        scale = Math.max(0.5f, Math.min(scale, 5.0f));

        if (scale != oldScale) {
            touchX = detector.getFocusX();
            touchY = detector.getFocusY();

            invalidate(0, 0, screenWidth, screenHeight);
        } 
        return true;
    }

}

public class GestureListener implements OnGestureListener {
    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2,
            float distanceX, float distanceY) {
                    //Helps in drag
        if (!scaleGesture.isInProgress()) {
            horizontalOffset -= distanceX;
            verticalOffset -= distanceY;

            invalidate();
            return true;
        }
        return false;
    }

}

@Override
public boolean onTouchEvent(MotionEvent event) {
    boolean result = scaleGesture.onTouchEvent(event);
    boolean isScaling = result = scaleGesture.isInProgress();
    if (!isScaling) {
        if (!(event.getPointerCount() > 1)) {
            result = gestures.onTouchEvent(event);
        } else
            result = false;
    }
    return result;
}

}

如果我将 scale 的值设置为 1.0f,这会很顺利。当我将 scale 的值更改为(例如)0.6f 时,它会传输到一个新位置,然后完美运行。

4

2 回答 2

3

请在此处查看@ToreRudberg 的答案-您可能需要修改代码以纠正您观察到的行为。

于 2013-10-24T02:00:47.933 回答
1

这是因为您的缩放轴坐标(touchX 和 touchY)最初为 0,当您第一次缩放时,它会突然将它们更改为缩放手势的焦点:

        touchX = detector.getFocusX();
        touchY = detector.getFocusY();

它适用于 1.0 初始比例,因为 1.0f 比例不会改变任何内容,因此您在开始时看不到突然的枢轴跳跃。

于 2013-10-20T00:28:53.043 回答