其他分享
首页 > 其他分享> > android-canvas.scale(scale,scale,px,py)跳到新位置

android-canvas.scale(scale,scale,px,py)跳到新位置

作者:互联网

我正在尝试在视图中同时使用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时,它将传输到新位置,然后完美工作.

解决方法:

请查看@ToreRudberg的答案here-您可能希望对代码进行修改以更正所观察到的行为.

标签:pinchzoom,android
来源: https://codeday.me/bug/20191030/1966786.html