android 可放缩的Mosaic 实例源码

Java基础

浏览数:90

2020-7-16

AD:资源代下载服务

:实现自定义view的放缩,完成马赛克的绘制


public boolean dispatchTouchEvent(MotionEvent event) {
super.dispatchTouchEvent(event);

float pointerX = 0,pointerY = 0;

int pointerCount = event.getPointerCount();
//计算多个触摸点的平均值
for (int i = 0; i < pointerCount; i ){
pointerX = event.getX(i);
pointerY = event.getY(i);
}
pointerX = pointerX / pointerCount;
pointerY = pointerY / pointerCount;
if (pointerCount > 1){
isMultiPointer = true;
//在多指模式,防误触变量重置
isCanDrawPath = false;
lastCheckDrawTime = 0;
}
if (lastPointerCount != pointerCount){
mLastX = pointerX;
mLastY = pointerY;
isCanDrag = false;
lastPointerCount = pointerCount;
}
//if (pointerCount > 1 || lastPointerCount >1){
if (isMultiPointer){
switch (event.getAction()){
case MotionEvent.ACTION_MOVE:
if (pointerCount == 1)
break;
if (mImageRect.width() > mInitImageRect.width()){ //仅仅在放大的状态,图片才可移动
int dx = (int) (pointerX – mLastX);
int dy = (int) (pointerY – mLastY);
if (!isCanDrag)
isCanDrag = isCanDrag(dx,dy);
if (isCanDrag) {
if (mImageRect.left dx > mInitImageRect.left)
dx = mInitImageRect.left – mImageRect.left;
if (mImageRect.right dx < mInitImageRect.right)
dx = mInitImageRect.right – mImageRect.right;
if (mImageRect.top dy > mInitImageRect.top)
dy = mInitImageRect.top – mImageRect.top;
if (mImageRect.bottom dy < mInitImageRect.bottom)
dy = mInitImageRect.bottom – mImageRect.bottom;
mImageRect.offset(dx, dy);
}
}
mLastX = pointerX;
mLastY = pointerY;
invalidate();
break;
case MotionEvent.ACTION_UP:
lastPointerCount = 0;
isMultiPointer = false;
break;
}
return true;
}
int action = event.getAction();
int x = (int) event.getX();
int y = (int) event.getY();
//防误触
if (!isCanDrawPath){
if(lastCheckDrawTime == 0){
lastCheckDrawTime = System.currentTimeMillis();
}
if (System.currentTimeMillis() – lastCheckDrawTime > 50){ //大于50ms为有效值
isCanDrawPath = true;
}
}
//Log.d(TAG, “action ” action ” x ” x ” y ” y);
if (mMode == Mode.GRID) {
onGridEvent(action, x, y);
} else if (mMode == Mode.PATH) {
onPathEvent(action, x, y);
}

return true;
}