Android 利用Matrix实现图片随手指平移、旋转、缩放

一、链接
Android 利用Matrix实现图片随手指平移、旋转、缩放—旋转

Android 利用Matrix实现图片随手指平移、旋转、缩放 —平移

Android 利用Matrix实现图片随手指平移、旋转、缩放—缩放

这篇是用来记录图片随手指缩放的。代码如下:


/**
 * 使用矩阵(Matrix)来设置图片的属性
 * 平移、旋转、放大缩小
 * 

* 本类的效果:縮放 * Created by lby on 2017/7/24. */ public class CropImageViewZoom extends AppCompatImageView { private Matrix matrix = new Matrix(); private Matrix currentMatrix = new Matrix(); private Bitmap bitmap; private float oldLength; // 按下時兩個落點的距離 private PointF midPoint = new PointF(); private boolean isMorePoint; // 是否是多根手指 public CropImageViewZoom(Context context) { this(context, null); } public CropImageViewZoom(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CropImageViewZoom(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.aaa); } @Override protected void onDraw(Canvas canvas) { canvas.save(); canvas.drawBitmap(bitmap, matrix, null); canvas.restore(); } @Override public boolean onTouchEvent(MotionEvent event) { // 注意:要想监听到ACTION_POINTER_DOWN和ACTION_POINTER_UP,必须有 MotionEvent.ACTION_MASK switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: isMorePoint = false; break; case MotionEvent.ACTION_POINTER_DOWN: isMorePoint = true; currentMatrix.set(matrix); oldLength = getLength(event); getMidPoint(midPoint, event); break; case MotionEvent.ACTION_MOVE: if (isMorePoint) { matrix.set(currentMatrix); // 计算缩放比例 float length = getLength(event) / oldLength; matrix.postScale(length, length, midPoint.x, midPoint.y); } invalidate(); break; case MotionEvent.ACTION_POINTER_UP: isMorePoint = false; break; case MotionEvent.ACTION_UP: break; default: break; } return true; } /** * 取手势中心点 */ private void getMidPoint(PointF point, MotionEvent event) { float x = event.getX(0) + event.getX(1); float y = event.getY(0) + event.getY(1); point.set(x / 2, y / 2); } /** * 获取两个落点之间的距离 */ private float getLength(MotionEvent event) { // 获取两个手指的点 float pointX1 = event.getX(0); float pointX2 = event.getX(1); float pointY1 = event.getY(0); float pointY2 = event.getY(1); return (float) Math.sqrt(Math.pow(pointX1 - pointX2, 2) + Math.pow(pointY1 - pointY2, 2)); } }

你可能感兴趣的:(android)