ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
下面这个代码实现的是用通过双指拉伸或者收缩实现图片的放大或者缩小。这里面注意几点: 1)多点触控的那些常量,这里面的知识参考博客: http://blog.csdn.net/barryhappy/article/details/7392326 2)Bitmap的回收机制。这里面多次创建Bitmap会引起内存不足,下面并没有解决这个问题,所以多次拉伸之后程序会挂掉。。 3)后记:这句话是后面加的。上面这个问题已经解决了,详情请看我的另一篇博客: http://blog.csdn.net/hhysirius/article/details/21525105 ~~~ package com.example.mytest; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.os.Bundle; import android.util.FloatMath; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ImageView; public class MainActivity extends Activity { private ImageView iv; private Bitmap bm; private Bitmap alterBm; private Bitmap temp; private Paint paint; private Matrix matrix; //旧的两指距离 private float oldDis = 0.0f; //新的两指距离 private float newDis = 0.0f; //判断是否是双指 private boolean flag = false; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); iv = (ImageView) this.findViewById(R.id.iv); bm = BitmapFactory.decodeResource(getResources(), R.drawable.xiamu); temp = bm.copy(bm.getConfig(), true); alterBm = bm.copy(bm.getConfig(), true); paint = new Paint(); paint.setColor(Color.BLACK); matrix = new Matrix(); iv.setImageBitmap(alterBm); iv.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub switch (event.getAction()&MotionEvent.ACTION_MASK) { //第一个手指按下 case MotionEvent.ACTION_DOWN: break; //第二个手指按下 case MotionEvent.ACTION_POINTER_DOWN: flag = true; oldDis = spacing(event); break; //手指移动 case MotionEvent.ACTION_MOVE: if (flag == false) { //仅有一个手指下不做反映 break; } newDis = spacing(event); //微小变化不作处理 if (newDis > (oldDis - 10.0f) && newDis < (oldDis + 10.0f)) { break; } float scale = newDis / oldDis; if (scale > 1) { float t = scale - 1.0f; t = t/2.0f; scale = scale - t; } if (scale < 1) { float t = 1.0f - scale; t = t/2.0f; scale = scale + t; } matrix.setScale(scale, scale); int newHeight = alterBm.getHeight(); int newWidth = alterBm.getWidth(); temp.recycle(); temp = Bitmap.createBitmap(alterBm, 0, 0, newWidth, newHeight, matrix ,true); iv.setImageBitmap(temp); alterBm.recycle(); alterBm = temp.copy(temp.getConfig(), true); newDis = oldDis; break; case MotionEvent.ACTION_POINTER_UP: flag = false; break; default: break; } 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); } } ~~~