使Activity实现GestureDetector.OnGestureListener,并重写其要实现的方法,在onFling方法中重写代码如下:
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
velocityX = velocityX > 4000 ? 4000:velocityX;
velocityX = velocityX < -4000 ? -4000:velocityX;
// 重新计算缩放比例
currentScale += currentScale * velocityX /4000.0f;
currentScale = currentScale > 0.1f ? currentScale : 0.1f;
// 重置matrix
matrix.reset();
matrix.setScale(currentScale,currentScale,100,150);
BitmapDrawable tmp = (BitmapDrawable) imageView.getDrawable();
// 将前一次缩放后的图片回收
if(!tmp.getBitmap().isRecycled()){
tmp.getBitmap().recycle();
}
// 下面这个Bitmap是从drawable文件夹中直接获取的,不能使用回收了的Bitmap我作为西面这句代码的参数
Bitmap newBitmap = Bitmap.createBitmap(bitmap,0,0,width,height,matrix,true);
imageView.setImageBitmap(newBitmap);
return true;
}
velocityX是在X方向上滑动的速度
if(!tmp.getBitmap().isRecycled()){
tmp.getBitmap().recycle();
}
上面这段代码涉及图片的回收,有利于减少内存的使用,在使用图片回收时,对图像做相关操作时一定要注意图像中的图片的来源问题