Android手势ImageView三部曲(一)

本文介绍了如何实现Android手势ImageView的拖拽和缩放效果,包括使用GestureImageView和PhotoView开源项目,以及通过Matrix进行图像操作。文章通过示例代码详细解释了手势检测和处理过程,并预告将探讨更深入的detector和GestureDetector。

前言:这几天一直在研究github上的PhotoView跟GestureImageView,发现写的都很牛,看了很久的代码,于是打算把自己所看的一些东西总结一下,内容还是很多的,但是很有含金量哈~~

先附上两个开源项目的链接:

GestureImageView: https://github.com/jasonpolites/gesture-imageview

PhotoView:https://github.com/chrisbanes/PhotoView

这样说有点乏味哈,先看看我们今天要实现的效果:

  1. 当一个手指按住图片的时候,此时的效果为拖拽的效果。
  2. 当两个手指按住图片的时候,手指旋转则图片跟着旋转,手指缩放则图片缩放。

效果图大致为(我模拟器不太好模拟旋转):

这里写图片描述

好了下面我们来实现一下这个手势缩放ImageView:

首先我们创建一个叫MatrixImageView的类去继承ImageView,然后重写其构造方法(我就不考虑直接new的情况了哈):

public class MatrixImageView2 extends ImageView {
   
   
 public MatrixImageView2(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }
}

然后我们需要定义几种当前view的状态:
MODE_NONE(初始状态);
MODE_DRAG(拖拽状态);
MODE_ZOOM(两个手指缩放状态)

public class MatrixImageView2 extends ImageView {
   
   
    private static final int MODE_NONE = 190;
    private static final int MODE_DRAG = 468;
    private static final int MODE_ZOOM = 685;
    .....
}

我们对ImageView做旋转、缩放、位移等操作主要是用到ImageView的这个方法:


    /**
     * Adds a transformation {@link Matrix} that is applied
     * to the view's drawable when it is drawn.  Allows custom scaling,
     * translation, and perspective distortion.
     *
     * @param matrix the transformation parameters in matrix form
     */
    public void setImageMatrix(Matrix matrix) {
        // collapse null and identity to just null
        if (matrix != null && matrix.isIdentity()) {
            matrix = null;
        }

        // don't invalidate unless we're actually changing our matrix
        if (matrix == null && !mMatrix.isIdentity() ||
                matrix != null && !mMatrix.equals(matrix)) {
            mMatrix.set(matrix);
            configureBounds();
            invalidate();
        }
    }

利用的是Matrix这个类(对这个类不懂的童鞋自己去查资料哈~),然后通过监听我们的onTouchEvent方法获取当前手势操作,然后对matrix进行相应操作,改变图片的状态。

代码比较短,而且我每行都注释了,我就直接给代码了:

MatrixImageView.java:

package com.leo.gestureimageview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.widget.ImageView;

public 
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值