【Android】多点触控(判断触摸点是否在view上)

来源:互联网 发布:两个矩阵相乘怎么算 编辑:程序博客网 时间:2024/04/29 15:58
【关键词】

Android 多点触控

【问题】
  • 如何获取单个触摸点的位置,多个触摸点的位置又如何获取呢?
  • 如何根据触摸点的位置,确定触摸点是否在 view 上?
【效果图】
【分析】
  • 通过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
}
// ~~~~~~~~~~~~~~~~~~~~
【参考资料】
  • Android L中水波纹点击效果的实现
0 0