本实例是通过《疯狂android讲义》上的范例:亲自打出来贴一下,从左往右手势是放大,从右往左是缩小
package com.example.demogesture; 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.GestureDetector.OnGestureListener; import android.view.MotionEvent; import android.widget.ImageView; public class MainActivity extends Activity implements OnGestureListener { // 定义手势检测器 GestureDetector detector; ImageView imageView; Bitmap bitmap;// 初始的图片资源 int width, height; float currentScale = 1;// 图片的缩放比 Matrix matrix;// 控制图片缩放的矩阵对象 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.activity_main); imageView = (ImageView) findViewById(R.id.imageView1); detector = new GestureDetector(this); matrix = new Matrix(); bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.aaa); width = bitmap.getWidth(); height = bitmap.getHeight(); // 设置imageView初始化时的图片,必须这样,如果改为bitmap后会报错 imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.aaa)); } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub return detector.onTouchEvent(event); } public boolean onDown(MotionEvent e) { // TODO Auto-generated method stub return false; } public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO Auto-generated method stub velocityX = velocityX > 4000 ? 4000 : velocityX; velocityX = velocityX < -4000 ? -4000 : velocityX; // 根据手势的速度来计算缩放比,如果velocityX>0,放大图像,否则缩小图像 currentScale += currentScale * velocityX / 4000.0f; // 保证currentScale不会为0 currentScale = currentScale > 0.01f ? currentScale : 0.01f; // 重置Matrix matrix.reset(); matrix.setScale(currentScale, currentScale, 160, 200); BitmapDrawable tmp = (BitmapDrawable) imageView.getDrawable(); // 如果图片还未回收,先强制回收图片 if (!tmp.getBitmap().isRecycled()) { tmp.getBitmap().recycle(); } // 根据原始位置和Matrix创建新图片 Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); imageView.setImageBitmap(bitmap2); return true; } public void onLongPress(MotionEvent e) { // TODO Auto-generated method stub } public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // TODO Auto-generated method stub return false; } public void onShowPress(MotionEvent e) { // TODO Auto-generated method stub } public boolean onSingleTapUp(MotionEvent e) { // TODO Auto-generated method stub return false; } }