缩放手势识别-ScaleGestureDetector

/ 0评 / 1

手势识别-GestureDetector中我们介绍了如何使用GestureDetector来识别用户的单击,双击,滑动等手势,然而在开发的过程中,我们有时需要识别用户缩放的手势,比如用户使用手指来缩放查看图片等,下面我来介绍一下如何使用ScaleGestureDetector来识别缩放手势。

ScaleGestureDetector的使用流程

ScaleGestureDetector的使用类似于GestureDetector。大致分为以下几步

ScaleGestureDetector的监听器

ScaleGestureDetector提供的事件监听器为:OnScaleGestureListener,对应如下几个方法。

//缩放事件执行

public boolean onScale(ScaleGestureDetector detector)

//缩放事件执行开始

//返回true表示继续接受缩放消息,调用onScale

//返回false表示不继续处理缩放消息,不会继续调用下面的回调函数。

public boolean onScaleBegin(ScaleGestureDetector detector)

//缩放事件执行结束

public void onScaleEnd(ScaleGestureDetector detector)

同样类似于GestureDetector,ScaleGestureDetector还提供了一个实现了OnScaleGestureListener接口的类SimpleOnScaleGestureListener,此类覆写了上面三个回调函数(空实现),我们可以继承SimpleOnScaleGestureListener,按照需求覆写响应的函数。

ScaleGestureDetector的常用方法

Demo

public class MainActivity extends ActionBarActivity {

	private ScaleGestureDetector mSGestureDetector;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mSGestureDetector = new ScaleGestureDetector(this,
				new MyScaleGestureListener());
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		mSGestureDetector.onTouchEvent(event);
		return super.onTouchEvent(event);
	}

	private class MyScaleGestureListener extends SimpleOnScaleGestureListener {

		@Override
		public boolean onScale(ScaleGestureDetector detector) {
			Log.v("x", "onScale");
			Log.v("x", "getCurrentSpan" + detector.getCurrentSpan());
			Log.v("x", "getPreviousSpan" + detector.getPreviousSpan());
			Log.v("x", "getScaleFactor" + detector.getScaleFactor());
			Log.v("x", "getEventTime" + detector.getEventTime());
			Log.v("x", "getTimeDelta" + detector.getTimeDelta());
			return super.onScale(detector);
		}

		@Override
		public boolean onScaleBegin(ScaleGestureDetector detector) {
			Log.v("x", "onScaleBegin");
			return false;
		}

		@Override
		public void onScaleEnd(ScaleGestureDetector detector) {
			Log.v("x", "onScaleEnd");
			super.onScaleEnd(detector);
		}
	}
}

发表评论

您的电子邮箱地址不会被公开。