Android 利用ScaleGestureDetector实现图片放大、缩小,单击双击操作

ScaleGestureDetector

用于处理缩放的工具类,用法与GestureDetector类似,都是通过onTouchEvent()关联相应的MotionEvent的。使用该类时,用户需要传入一个完整的连续不断地motion事件(包含ACTION_DOWN,ACTION_MOVE和ACTION_UP事件)。

下面贴一个仿微信朋友圈图片处理的工具类,复制可以直接用

/**
* 自定义手势放大  缩小  平移view
*/
@SuppressLint("AppCompatCustomView")
public class ScaleMoveImageViewer extends ImageView implements View.OnTouchListener,ScaleGestureDetector.OnScaleGestureListener {
   private ScaleGestureDetector sgc;
   private GestureDetector gd;
   private float SOURCE_SCALE;
   private	Matrix matrix=new Matrix();
   private float[] values=new float[9];
   private boolean once=true;
   private float preX,preY,currentX,currentY;
   private int prePointerCount;

   private static final int REQUESTCODE_BIGER=1;
   private static final int REQUESTCODE_SMALLER=2;
   private static final float BIGER_TMP_SCALE=1.06f;
   private static final float SMALLER_TMP_SCALE=0.94f;
   private static final float MAX_SCALE=4.0F;
   private static final float MIN_SCALE=0.2F;
   private Activity imageShower;
   public ScaleMoveImageViewer(Context context) {
       this(context,null);
   }
   public ScaleMoveImageViewer(final Context context, AttributeSet attrs) {
       super(context, attrs);
       this.imageShower= (Activity) context;
       super.setScaleType(ScaleType.MATRIX);
       this.setOnTouchListener(this);
       sgc=new ScaleGestureDetector(context, this);
       gd=new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
           @Override
           public boolean onDoubleTap(MotionEvent e) {
               Log.i("TAG","onDoubleTap");
               //处理双击事件
               float x=e.getX();
               float y=e.getY();
               setDobleTapScale(x, y);
               return true;
           }
           @Override
           public boolean onSingleTapConfirmed(MotionEvent e) {
               //处理单击关闭页面
               imageShower.finish();
               return super.onSingleTapConfirmed(e);
           }
       });

   }

   //手指缩放
   @Override
   public boolean onScale(ScaleGestureDetector detector) {
       float scaleFactor=detector.getScaleFactor();
       float currentScale=getScale();//相对原图的缩放比例
       if(currentScale>MAX_SCALE && scaleFactor<1.0f || currentScale<MIN_SCALE
               && scaleFactor>1.0f || currentScale<MAX_SCALE && currentScale>MIN_SCALE){
           matrix.postScale(scaleFactor, scaleFactor, detector.getFocusX(), detector.getFocusY());
       }
       ImagePositonManager.setShowPosition(getDrawable(), matrix, getWidth(), getHeight());
       setImageMatrix(matrix);
       return true;
   }

   //移动
   @Override
   public boolean onTouch(View v, MotionEvent event) {
       currentX=0;currentY=0;
       int pointerCount=event.getPointerCount();
       for(int i=0;i<pointerCount;i++){
           currentX+=event.getX();
           currentY+=event.getY();
       }
       currentX/=pointerCount;
       currentY/=pointerCount;
       if (pointerCount!=prePointerCount) {
           preX=currentX;
           preY=currentY;
           prePointerCount=pointerCount;
       }
       switch (event.getAction()) {
           case MotionEvent.ACTION_MOVE:
               float dx=currentX-preX;
               float dy=currentY-preY;
               ImagePositonManager.setMovePosition(getDrawable(), matrix, dx, dy, getWidth(), getHeight());
               setImageMatrix(matrix);
               preX=currentX;
               preY=currentY;
               break;
           case MotionEvent.ACTION_UP://有多根手指触摸屏幕时,只有当所有的手指抬起时这里才执行
               prePointerCount=0;
               break;
       }
       gd.onTouchEvent(event);
       return sgc.onTouchEvent(event);
   }
   //双击缩放
   public void setDobleTapScale(float px,float py){
       float currectScale=getScale();
       if(currectScale<SOURCE_SCALE){
           ScaleMoveImageViewer.this.postDelayed(new AutoScaleRunnable(SOURCE_SCALE, px, py,REQUESTCODE_BIGER), 10);
       }
       if(currectScale==SOURCE_SCALE){
           ScaleMoveImageViewer.this.postDelayed(new AutoScaleRunnable(MAX_SCALE-1, px, py,REQUESTCODE_BIGER), 10);
       }
       if(currectScale>SOURCE_SCALE){
           ScaleMoveImageViewer.this.postDelayed(new AutoScaleRunnable(SOURCE_SCALE, px, py,REQUESTCODE_SMALLER), 10);
       }
       ImagePositonManager.setShowPosition(getDrawable(), matrix, getWidth(), getHeight());
       setImageMatrix(matrix);
   }

   private class AutoScaleRunnable implements Runnable{

       float targetScale=0;
       float px=0;
       float py=0;
       int requestCode=0;
       public AutoScaleRunnable(float targetScale,float px,float py,int requestCode){
           this.targetScale=targetScale;
           this.px=px;
           this.py=py;
           this.requestCode=requestCode;
       }

       @Override
       public void run() {
           if(requestCode==REQUESTCODE_BIGER){
               matrix.postScale(BIGER_TMP_SCALE, BIGER_TMP_SCALE, px, py);
               ImagePositonManager.setShowPosition(getDrawable(), matrix, getWidth(), getHeight());
               setImageMatrix(matrix);
               float currentScale = getScale();
               if (currentScale<targetScale) {
                   ScaleMoveImageViewer.this.postDelayed(this, 10);
               }else {
                   while(getScale()!=targetScale){
                       matrix.postScale(targetScale/getScale(), targetScale/getScale(), px, py);
                       ImagePositonManager.setShowPosition(getDrawable(), matrix, getWidth(), getHeight());
                       setImageMatrix(matrix);
                   }
               }
           }
           else if (requestCode==REQUESTCODE_SMALLER) {
               matrix.postScale(SMALLER_TMP_SCALE, SMALLER_TMP_SCALE, px, py);
               ImagePositonManager.setShowPosition(getDrawable(), matrix, getWidth(), getHeight());
               setImageMatrix(matrix);
               float currentScale = getScale();
               if(currentScale>targetScale){
                   ScaleMoveImageViewer.this.postDelayed(this, 10);
               }else {
                   while(getScale()!=targetScale){
                       matrix.postScale(targetScale/getScale(), targetScale/getScale(), px, py);
                       ImagePositonManager.setShowPosition(getDrawable(), matrix, getWidth(), getHeight());
                       setImageMatrix(matrix);
                   }
               }
           }
       }
   }

   @Override
   protected void onDraw(Canvas canvas) {
       if(once){
          if (getDrawable()==null){
               return;
           }
           matrix=getImageMatrix();
           once=false;
           Drawable drawable=getDrawable();
           //获取图片的宽和高
           int dw=drawable.getIntrinsicWidth();
           int dh=drawable.getIntrinsicHeight();
           int w=getWidth();
           int h=getHeight();
           float scale=Math.min(1.0f*w/dw, 1.0f*h/dh);
           SOURCE_SCALE=scale;
           matrix.postTranslate(w/2-dw/2, h/2-dh/2);
           matrix.postScale(scale, scale, w/2, h/2);
           setImageMatrix(matrix);
       }
       super.onDraw(canvas);
   }

   private float getScale(){
       matrix.getValues(values);
       return values[Matrix.MSCALE_X];
   }

   @Override
   public boolean onScaleBegin(ScaleGestureDetector detector) {
       return true;

   }

   @Override
   public void onScaleEnd(ScaleGestureDetector detector) {

   }
}
public class ImagePositonManager {

   //缩放图片时控制其显示位置
   public static void setShowPosition(Drawable drawable, Matrix matrix, int w, int h){
       RectF rectF=new RectF(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
       matrix.mapRect(rectF);
       float rw=rectF.width();
       float rh=rectF.height();
       float moveX=0,moveY=0;
       if(rw<=w){
           moveX=w/2-rw/2-rectF.left;
       }
       if (rh<=h) {
           moveY=h/2-rh/2-rectF.top;
       }
       if(rw>w && rectF.left>0){
           moveX=-rectF.left;
       }
       if(rw>w && rectF.right<w){
           moveX=w-rectF.right;
       }
       if(rh>h && rectF.top>0){
           moveY=-rectF.top;
       }
       if(rh>h && rectF.bottom<h){
           moveY=h-rectF.bottom;
       }
       matrix.postTranslate(moveX, moveY);
   }

   //移动图片时控制显示位置
   public static void setMovePosition(Drawable drawable, Matrix matrix, float dx, float dy, int w, int h){
       RectF rectF=new RectF(0,0,drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
       matrix.mapRect(rectF);
       float rw=rectF.width();
       float rh=rectF.height();
       if(rw>w && rectF.left+dx<=0 && rectF.right+dx>=w){
           matrix.postTranslate(dx, 0);
       }
       if(rh>h && rectF.top+dy<=0 && rectF.bottom+dy>=h){
           matrix.postTranslate(0, dy);
       }
   }

}

如果本篇文章帮到你了,请帮忙点下赞,谢谢!

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
要在uni-app中实现图片双指或双击放大缩小的功能,你可以使用uni-app提供的`uni.createSelectorQuery()`和`canvas` API来实现。 具体实现步骤如下: 1. 在`<template>`标签中放置一个`<canvas>`标签,用于显示图片; 2. 在`<script>`标签中,使用`uni.createSelectorQuery()`方法获取`<canvas>`标签的上下文`canvasContext`; 3. 使用`canvasContext.drawImage()`方法绘制图片; 4. 监听`<canvas>`标签的`touchstart`、`touchmove`、`touchend`事件,分别处理双指缩放和双击放大的逻辑; 5. 在事件处理函数中,使用`canvasContext.scale()`方法实现双指缩放,使用`canvasContext.translate()`和`canvasContext.scale()`方法实现双击放大。 以下是示例代码: ``` <template> <canvas style="width:100%;height:100%;" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd"></canvas> </template> <script> export default { data() { return { canvasContext: null, // canvas上下文 imgWidth: 0, // 图片宽度 imgHeight: 0, // 图片高度 imgScale: 1, // 图片缩放比例 lastTouchDistance: 0, // 上一次双指触摸距离 lastTouchTime: 0, // 上一次触摸时间 lastTouchX: 0, // 上一次触摸x坐标 lastTouchY: 0 // 上一次触摸y坐标 }; }, mounted() { // 获取canvas上下文 uni.createSelectorQuery().select('canvas').fields({ node: true, size: true }).exec((res) => { this.canvasContext = res[0].node.getContext('2d'); }); // 加载图片 let img = new Image(); img.src = '图片地址'; img.onload = () => { // 计算图片宽高和缩放比例 this.imgWidth = img.width; this.imgHeight = img.height; this.imgScale = Math.min(uni.upx2px(750) / this.imgWidth, uni.upx2px(750) / this.imgHeight); // 绘制图片 this.canvasContext.drawImage(img, 0, 0, this.imgWidth * this.imgScale, this.imgHeight * this.imgScale); }; }, methods: { touchStart(e) { if (e.touches.length === 2) { // 双指触摸,记录初始触摸距离 this.lastTouchDistance = Math.sqrt(Math.pow(e.touches[1].pageX - e.touches[0].pageX, 2) + Math.pow(e.touches[1].pageY - e.touches[0].pageY, 2)); } else if (e.touches.length === 1) { // 单指触摸,记录触摸时间和坐标 let currentTime = new Date().getTime(); if (currentTime - this.lastTouchTime < 300 && Math.abs(e.touches[0].pageX - this.lastTouchX) < 30 && Math.abs(e.touches[0].pageY - this.lastTouchY) < 30) { // 双击触摸,放大图片 this.canvasContext.translate((e.touches[0].pageX - this.imgWidth * this.imgScale / 2) * (1 - 1.5), (e.touches[0].pageY - this.imgHeight * this.imgScale / 2) * (1 - 1.5)); this.canvasContext.scale(1.5, 1.5); this.imgScale *= 1.5; this.lastTouchTime = 0; } else { // 单击触摸,记录触摸时间和坐标 this.lastTouchTime = currentTime; this.lastTouchX = e.touches[0].pageX; this.lastTouchY = e.touches[0].pageY; } } }, touchMove(e) { if (e.touches.length === 2) { // 双指触摸,计算触摸距离差值 let touchDistance = Math.sqrt(Math.pow(e.touches[1].pageX - e.touches[0].pageX, 2) + Math.pow(e.touches[1].pageY - e.touches[0].pageY, 2)); let distanceDelta = touchDistance - this.lastTouchDistance; if (distanceDelta !== 0) { // 缩放图片 let scaleDelta = distanceDelta / uni.upx2px(750) * 2; this.canvasContext.translate((e.touches[0].pageX + e.touches[1].pageX) / 2 - this.imgWidth * this.imgScale / 2, (e.touches[0].pageY + e.touches[1].pageY) / 2 - this.imgHeight * this.imgScale / 2); this.canvasContext.scale(1 + scaleDelta, 1 + scaleDelta); this.canvasContext.translate(this.imgWidth * this.imgScale / 2 - (e.touches[0].pageX + e.touches[1].pageX) / 2, this.imgHeight * this.imgScale / 2 - (e.touches[0].pageY + e.touches[1].pageY) / 2); this.imgScale *= 1 + scaleDelta; this.lastTouchDistance = touchDistance; } } }, touchEnd(e) { this.lastTouchDistance = 0; } } }; </script> ``` 注意,以上代码仅供参考,具体实现还需要根据实际情况进行调整。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值