我正在尝试在视图中使用scalegesture listener和gesturelistener。如果比例为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时,它会传输到一个新位置,然后完美地运行。
答案 0 :(得分:3)
请通过@ToreRudberg here查看答案 - 您可能希望改进代码以纠正您观察到的行为。
答案 1 :(得分:1)
这是因为您的缩放枢轴坐标(touchX和touchY)最初为0,当您第一次缩放时,它会突然将它们更改为缩放手势的焦点:
touchX = detector.getFocusX();
touchY = detector.getFocusY();
它适用于1.0初始比例,因为1.0f比例不会改变任何东西,所以你不会在开始时看到突然的枢轴跳跃。