手势和图片控件一起使用,实现滑动手机缩放图片:
含滚动条时,手势的onFling方法无效
图片不要过大,不然缩放时可能出现内存
package practise.lxm.hello;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ImageView;
/**
* 滑动缩放图片
*/
public class MainActivity extends Activity
implements GestureDetector.OnGestureListener{
GestureDetector gestureDetector;
ImageView ivMain;
//图片信息
Bitmap bitmap;
int bitmapWidth;
int bitmapHeigh;
//当前缩放
float scaleX = 1; //x缩放
float scaleY = 1; //y缩放
//用于操作图片缩放
Matrix matrix;
//最快速度
final int maxSpeed = 4000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ivMain = (ImageView)findViewById(R.id.iv_main);
gestureDetector = new GestureDetector(this,this);
matrix = new Matrix();
//初始化图片信息
bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.big)).getBitmap() ;
bitmapWidth = bitmap.getWidth();
bitmapHeigh = bitmap.getHeight();
ivMain.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.big));
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
velocityX =velocityX>maxSpeed? maxSpeed:
velocityX < -maxSpeed ? -maxSpeed:
velocityX;
velocityY =velocityY>maxSpeed? maxSpeed:
velocityY < -maxSpeed ? -maxSpeed:
velocityY;
//计算新的缩放,缩放不能=0
scaleX += velocityX/maxSpeed;
scaleY += velocityY/maxSpeed;
scaleX = scaleX >= 0.01f ?scaleX:0.01f;
scaleY = scaleY >= 0.01f ?scaleY:0.01f;
//回收图片
Bitmap imgBitmap = ((BitmapDrawable)ivMain.getDrawable()).getBitmap();
if(!imgBitmap.isRecycled()){
imgBitmap.recycle();
}
//缩放图片
matrix.reset(); //还原
matrix.setScale(scaleX,scaleY,bitmapWidth/2,bitmapHeigh/2);
Bitmap scaleBitmap = Bitmap.createBitmap(bitmap, 0,0,bitmapWidth,bitmapHeigh,matrix,true);
//显示新的图片
ivMain.setImageBitmap(scaleBitmap);
return true;
}
public boolean onTouchEvent(MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
}