我有一个ImageView,我添加了一个OnTouchListener,这样我就可以用两个手指捏合手势放大和缩小后者。我正在使用下面的代码,但我在调整实际位图大小时遇到问题。后者变得模糊,保持相同的大小,并与图像的调整大小版本重叠,就像它只是将新图像放在旧图像之上而不是替换它。我认为drawMatrix方法存在问题......
int touchState;
final int IDLE = 0;
final int TOUCH = 1;
final int PINCH = 2;
float dist0, distCurrent;
public boolean onTouch(View view, MotionEvent event) {
boolean handledHere = false;
float distx, disty;
final int action = event.getAction();
switch(action & MotionEvent.ACTION_MASK){
case MotionEvent.ACTION_DOWN:
//A pressed gesture has started, the motion contains the initial starting location.
touchState = TOUCH;
break;
case MotionEvent.ACTION_POINTER_DOWN:
//A non-primary pointer has gone down.
touchState = PINCH;
//Get the distance when the second pointer touch
distx = event.getX(0) - event.getX(1);
disty = event.getY(0) - event.getY(1);
dist0 = FloatMath.sqrt(distx * distx + disty * disty);
break;
case MotionEvent.ACTION_MOVE:
//A change has happened during a press gesture (between ACTION_DOWN and ACTION_UP).
if(touchState == PINCH){
//Get the current distance
distx = event.getX(0) - event.getX(1);
disty = event.getY(0) - event.getY(1);
distCurrent = FloatMath.sqrt(distx * distx + disty * disty);
drawMatrix((ImageView) view);
}
break;
case MotionEvent.ACTION_UP:
//A pressed gesture has finished.
touchState = IDLE;
break;
case MotionEvent.ACTION_POINTER_UP:
//A non-primary pointer has gone up.
touchState = TOUCH;
break;
}
return handledHere;
}
private void drawMatrix(ImageView view){
float curScale = distCurrent/dist0;
if (curScale < 0.1){
curScale = 0.1f;
}
view.buildDrawingCache();
Bitmap originalBitmap = view.getDrawingCache();
Bitmap resizedBitmap;
int newHeight = (int) (view.getHeight() * curScale);
int newWidth = (int) (view.getWidth() * curScale);
resizedBitmap = Bitmap.createScaledBitmap(originalBitmap, newWidth, newHeight, false);
view.setImageBitmap(resizedBitmap);
}
当我多次放大和缩小时,这就是它的变化......
感谢您的帮助。
答案 0 :(得分:1)
Actualy你正在调用onmove中的draw函数,所以当你移动你的手指时它会继续调用它。所以用新的高度和宽度生成的图像都被设置为imageview,这是alredy set der。在将调整大小后的图像设置为imageview之前,请尝试删除所有视图。希望这可以解决您的问题。
private void drawMatrix(ImageView view){
float curScale = distCurrent/dist0;
if (curScale < 0.1){
curScale = 0.1f;
}
view.buildDrawingCache();
Bitmap originalBitmap = view.getDrawingCache();
Bitmap resizedBitmap;
int newHeight = (int) (view.getHeight() * curScale);
int newWidth = (int) (view.getWidth() * curScale);
resizedBitmap = Bitmap.createScaledBitmap(originalBitmap, newWidth, newHeight, false);
view.removeallviews();
view.setImageBitmap(resizedBitmap);
}
答案 1 :(得分:0)
您可以使用TouchImageView类[https://github.com/MikeOrtiz/TouchImageView/blob/master/src/com/example/touch/TouchImageView.java]。 这为图像视图提供了很好的放大和缩小功能。