Android实战之手势与多点触控探究
一、提要
实施上它的功能非常的简单,类似一个ToDoList,但它将用户体验做到了极致,其中一个最大的特点就是将手势和多点触控成功得融入到了应用之中。
这篇文章要探究的就是在Android中的手势和多点触控的原理及实现。
二、最原始的单点拖拽和两点缩放
原理:对于常规的控件触控操作,在setOnTouchListener()接口中,实现 onTouchEvent()方法来处理。
效果:
代码清单:
[java]
package com.example.multitouch;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.Toast;
import android.view.GestureDetector.OnGestureListener;
public class MainActivity extends Activity implements OnTouchListener{
public ImageView myImageView;
private static final int NONE = 0;
private static final int DRAG = 1;
private static final int ZOOM = 2;
private int mode = NONE;
private Matrix tmpMatrix=new Matrix();;
private Matrix savedMatrix = new Matrix();
private PointF startPoint = new PointF();
private PointF endPoint=new PointF();
private PointF midPoint = new PointF();
private float oldDistance;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myImageView=(ImageView)findViewById(R.id.myImageView);
myImageView.setOnTouchListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
//获取触控的点数
int pointCount = event.getPointerCount();
switch(event.getAction() & MotionEvent.ACTION_MASK){
//单手指按下
case MotionEvent.ACTION_DOWN:
//将当前的坐标保存为起始点
startPoint.set(event.getX(), event.getY());
tmpMatrix.set(myImageView.getImageMatrix());
savedMatrix.set(tmpMatrix);
mode = DRAG;
break;
//第二根手指按下
case MotionEvent.ACTION_POINTER_DOWN:
oldDistance = (float) Math.sqrt((event.getX(0) - event.getX(1)) * (event.getX(0) - event.getX(1)) + (event.getY(0) - event.getY(1)) * (event.getY(0) - event.getY(1)));
if (oldDistance > 10f)
{
savedMatrix.set(tmpMatrix);
midPoint.set((event.getX(0) + event.getX(1))/2, (event.getY(0) + event.getY(1))/2);
mode = ZOOM;
}
break;
//指点杆保持按下,并且进行位移
case MotionEvent.ACTION_MOVE:
//拖拽模式
if (mode == DRAG) {
tmpMatrix.set(savedMatrix);
tmpMatrix.postTranslate(event.getX() - startPoint.x, event.getY()
- startPoint.y);
}
//缩放模式
else if (mode == ZOOM)
{
float newDist = (float) Math.sqrt((event.getX(0) - event.getX(1)) * (event.getX(0) - event.getX(1)) + (event.getY(0) - event.getY(1)) * (event.getY(0) - event.getY(1)));
 
补充:移动开发 , Android ,