图片预览功能几乎是每个APP里面都要用到的,看似简单,做完这个小demo你一定可以熟悉View的各种手势相关的操作。 需要实现的功能有手势缩放,双击图片缩放,放大后滑动查看,惯性滑动等。 通过对功能的分析可知我们需要的工具类有:Matrix(实现图片的移动等一些列变换),GestureDetector(实现对滑动、单击、双击、fling等手势处理),ScaleGestureDetector(实现对缩放动作的处理) 准备工作:首先想要让着两个手势处理的类起到作用,需要复写OnTouchEvent方法
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean retVal = mScaleGestureDetector.onTouchEvent(event);
retVal = mGestureDetector.onTouchEvent(event) || retVal;
return retVal || super.onTouchEvent(event);
}
而这两个手势处理类在初始化的时候分别需要传递各自监听手势的监听器, ScaleGestureDetector.OnScaleGestureListener和 GestureDetector.OnGestureListener 它们当中包含了各种手势的回调方法,如果我们不想监听每种手势可以使用其对应的OnSimple****GestureListener来选择性的复写某个方法。具体不熟悉的地方可以查看http://hukai.me/android-training-course-in-chinese/input/gestures/detector.html手势检测的Android官方培训课
第一个功能、实现图片经过缩放手势的放大缩小功能 首先我们要复写ScaleGestureDetector.OnScaleGestureListene的onScale方法
@Override
public boolean onScale(ScaleGestureDetector detector) {
//得到缩放中心
float focusX = detector.getFocusX();
float focusY = detector.getFocusY();
float targetScale = getScale(mScaleMatrix) * detector.getScaleFactor();
//不要让缩放比例太小或者太大
targetScale = Math.max(getMinScale(), Math.min(targetScale, getMaxScale()));
zoomTo(targetScale,focusX,focusY);
invalidate();
return true;
}
其中的getScale方法是通过matrix获得x方向上长度
public float getScale(Matrix matrix) {
//获取各个方向上的值
matrix.getValues(matrixValues);
return this.matrixValues[0];
}
关键变换是在zoomTo方法:
private void zoomTo(float scale, float centerX, float centerY) {
if(scale > this.getMaxScale()) {
scale = this.getMaxScale();
}
float oldScale = this.getScale(mScaleMatrix);