Android
多点触控
MotionEvent
可以获取到触摸点个数;MotionEvent.getX(int pointerIndex)
方法,可以获取到指定触摸点的X值;对于Y坐标同理;// -------------------- action:multi-touch time:2016.04.15 by:Lou
// 重写 Activity 的 onTouchEvent方法;
@Override
public boolean onTouchEvent(MotionEvent event) {
whenTouchMove(event);
if (event.getAction() == MotionEvent.ACTION_UP) {
whenTouchUp();
}
return true;
}
private void whenTouchMove(MotionEvent event) {
Point[] points = getCurrentPoints(event);
//根据四个触摸点对四个view进行各自的处理;
doResultWithPoints(mIvIndicatorTopLeft, points);
doResultWithPoints(mIvIndicatorTopRight, points);
doResultWithPoints(mIvIndicatorBottomLeft, points);
doResultWithPoints(mIvIndicatorBottomRight, points);
}
private static final int MAX_TOUCH_POINT = 4; // 最多监听4个触点;
// 获取当前所有触摸点的位置;
public static Point[] getCurrentPoints(MotionEvent event){
int pointerCount = event.getPointerCount();
if (pointerCount > MAX_TOUCH_POINT) {
pointerCount = MAX_TOUCH_POINT;
}
Point[] points = new Point[pointerCount];
for (int i = 0; i < pointerCount; i++) {
points[i] = new Point((int) event.getX(i), (int) event.getY(i));
}
return points;
}
// 判断一组触摸点是否在 view上;
public static boolean isTouchPointInView(View view, Point[] points) {
if (view == null && points == null) {
throw new NullPointerException();
}
int len = points.length;
boolean result = false;
for (int i = 0; i < len; i++) {
if (isTouchPointInView(view, points[i])) {
result = true;
break;
}
}
return result;
}
// 判断一个具体的触摸点是否在 view 上;
public static boolean isTouchPointInView(View view, Point point) {
if (view == null && point == null) {
throw new NullPointerException();
}
int[] location = new int[2];
view.getLocationOnScreen(location);
int left = location[0];
int top = location[1];
int right = left + view.getMeasuredWidth();
int bottom = top + view.getMeasuredHeight();
if (point.x >= left && point.x <= right && point.y >= top && point.y <= bottom) {
return true;
}
return false;
}
// 根据触摸点是否在 view 上进行处理;
private void doResultWithPoints(ImageView iv, Point[] points) {
boolean result = isTouchPointInView(iv, points);
if (result) { // 在范围内:
// TODO
} else { // 不在范围内:
// TODO
}
}
// 当所有触摸点都松开的时候执行;
private void whenTouchUp() {
// TODO
}
// ~~~~~~~~~~~~~~~~~~~~