所以我遇到了图像将放大的错误,但不是放大到我的两个手指的中点,而是放大到原始图片的角落。这会创建一个非常不自然的用户界面。
@Override
protected void onDraw(Canvas canvas) {
canvas.save();
canvas.translate(mPosX, mPosY);
canvas.scale(mScaleFactor, mScaleFactor);
super.onDraw(canvas);
canvas.restore();
}
使用我的 onTouchEvent,myScale.onTouch 会将程序发送到 scaleListener 以获取缩放信息
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
midPoint(mid,event);
myScale.onTouchEvent(event);
switch (event.getAction() & MotionEvent.ACTION_MASK){
case MotionEvent.ACTION_DOWN: {
final float x = event.getX();
final float y = event.getY();
mode=DRAG;
// Remember where we started
mLastTouchX = x;
mLastTouchY = y;
mActivePointerId = event.getPointerId(0);
break;
}
case MotionEvent.ACTION_POINTER_DOWN: {
final float gx = myScale.getFocusX();
final float gy = myScale.getFocusY();
mLastGestureX=gx;
mLastGestureY=gy;
mode=ZOOM;
break;
}
case MotionEvent.ACTION_MOVE: {
final int pointerIndex = event.findPointerIndex(mActivePointerId);
final float x = event.getX(pointerIndex);
final float y = event.getY(pointerIndex);
// Calculate the distance moved
if(!myScale.isInProgress()){
// Move the object
final float dx = x - mLastTouchX;
final float dy = y - mLastTouchY;
mPosX += dx;
mPosY += dy;
// Remember this touch position for the next move event
// Invalidate to request a redraw
invalidate();
}
mLastTouchX = x;
mLastTouchY = y;
break;
}
I have deleted action up and action pointer up because they have nothing to do with this problems
}
invalidate();
return true;
}
private float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
private void midPoint(PointF point, MotionEvent event) {
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
// Don't let the object get too small or too large.
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 10.0f));
float currentdist=detector.getCurrentSpan();
float last=detector.getPreviousSpan();
float ratio = currentdist/last;
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));
Matrix temp = new Matrix();
temp.postScale(ratio, ratio, mid.x,mid.y);
temp.preConcat(matrix);
matrix=temp;
invalidate();
return true;
}
}