Android 手势识别—缩放
上一篇讲解了手势识别中的点击和双击事件的识别,用到的是GestureDetector类和GestureDetectorCompat类,用于监听用户触摸屏幕中的简单动作。
缩放
基本用法如下,可以通过缩放手势缩放一个View
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class ScaleGestureActivity extends BaseActivity { private View mView; private ScaleGestureDetector mScaleGestureDetector; private static final String TAG = "ScaleGestureActivity"; private float mScaleFactor = 1.0f; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scale_gesture); mView = findViewById(R.id.scale_view); mScaleGestureDetector = new ScaleGestureDetector(this,mScaleGestureListener); } @Override public boolean onTouchEvent(MotionEvent event) { mScaleGestureDetector.onTouchEvent(event); return super.onTouchEvent(event); } private ScaleGestureDetector.OnScaleGestureListener mScaleGestureListener = new ScaleGestureDetector.OnScaleGestureListener() { @Override public boolean onScale(ScaleGestureDetector scaleGestureDetector) { mScaleFactor *= scaleGestureDetector.getScaleFactor(); mView.setScaleX(mScaleFactor); mView.setScaleY(mScaleFactor); Log.i(TAG, "onScale: "+ scaleGestureDetector.getScaleFactor()+"----"+mScaleFactor); return true; } @Override public boolean onScaleBegin(ScaleGestureDetector scaleGestureDetector) { return true; } @Override public void onScaleEnd(ScaleGestureDetector scaleGestureDetector) { } }; }
ScaleGestureDetector 官方对该类的解释如下:
Detects scaling transformation gestures using the supplied
MotionEvent
s. TheScaleGestureDetector.OnScaleGestureListener
callback will notify users when a particular gesture event has occurred. This class should only be used withMotionEvent
s reported via touch. To use this class:
- Create an instance of the
ScaleGestureDetector
for yourView
- In the
onTouchEvent(MotionEvent)
method ensure you callonTouchEvent(MotionEvent)
. The methods defined in your callback will be executed when the events occur.
该类的构造方法如下:
public ScaleGestureDetector(Context context, ScaleGestureDetector.OnScaleGestureListener listener)
由构造方法可知需要为一个缩放类设置一个缩放的监听接口,具体实现见代码中监听类接口的实现,下面具体介绍几个函数的含义:
- public boolean onScale(ScaleGestureDetector detector);
缩放时会被调用,返回值代表本次缩放事件是否已被处理。如果已被处理,那么detector就会重置缩放事件;如果未被处理,detector会继续进行计算,修改getScaleFactor()的返回值,直到被处理为止。因此,它常用在判断只有缩放值达到一定数值时才进行缩放。下面的代码表示只有当缩放倍数达到2倍时才对其进行缩放,否则该事件不处理。
public boolean onScale(ScaleGestureDetector detector) { System.out.println(detector.getScaleFactor()); if(detector.getScaleFactor()< 2){ return false; } mMatrix.preScale(detector.getScaleFactor(), detector.getScaleFactor()); setImageMatrix(mMatrix); return true; }
2.public boolean onScaleBegin(ScaleGestureDetector detector)
缩放开始时会被调用。返回值表示该detector是否处理后继的缩放事件。返回false时,不会执行后续的onScale()。
3. public void onScaleEnd(ScaleGestureDetector scaleGestureDetector)
缩放结束时的回调
http://blog.csdn.net/qiwenmingshiwo/article/details/70850406