invalidate里放着ONDRAW的方法,当调用I时,会自动更新图片
如果上次记录的位置在-1,那么就更新为现在的位置,更新后就不再为-1了,就不再变了
也就是说是保留第一次触碰到的位置
public class CustomView extends View {
private int mLastX, mLastY;
private boolean isDragging = false;
public CustomView(Context context) {
super(context);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
int currX = (int) event.getX();
int currY = (int) event.getY();
switch (action) {
case MotionEvent.ACTION_DOWN:
if (event.getPointerCount() == 1) {
isDragging = true;
}
mLastX = currX;
mLastY = currY;
break;
case MotionEvent.ACTION_MOVE:
if (isDragging) {
int dx = currX - mLastX;
int dy = currY - mLastY;
// 拖拽
int left = getLeft() + dx;
int top = getTop() + dy;
int right = getRight() + dx;
int bottom = getBottom() + dy;
layout(left, top, right, bottom);
} else {
int dx = currX - mLastX;
int dy = currY - mLastY;
// 拉伸
ViewGroup.LayoutParams layoutParams = getLayoutParams();
layoutParams.width += dx;
layoutParams.height += dy;
setLayoutParams(layoutParams);
}
mLastX = currX;
mLastY = currY;
break;
case MotionEvent.ACTION_UP:
isDragging = false;
break;
}
return true;
}
}
public class CustomView extends View {
private int mLastX, mLastY;
private boolean isDragging = false;
private boolean isScaling = false;
private float initialDistance;
public CustomView(Context context) {
super(context);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
int currX = (int) event.getX();
int currY = (int) event.getY();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
if (event.getPointerCount() == 1) {
isDragging = true;
}
mLastX = currX;
mLastY = currY;
break;
case MotionEvent.ACTION_POINTER_DOWN:
if (event.getPointerCount() == 2) {
isDragging = false;
isScaling = true;
initialDistance = getDistance(event);
}
break;
case MotionEvent.ACTION_MOVE:
if (isDragging) {
int dx = currX - mLastX;
int dy = currY - mLastY;
// 拖拽
int left = getLeft() + dx;
int top = getTop() + dy;
int right = getRight() + dx;
int bottom = getBottom() + dy;
layout(left, top, right, bottom);
} else if (isScaling) {
float currentDistance = getDistance(event);
float scale = currentDistance / initialDistance;
// 拉伸
ViewGroup.LayoutParams layoutParams = getLayoutParams();
layoutParams.width *= scale;
layoutParams.height *= scale;
setLayoutParams(layoutParams);
}
break;
case MotionEvent.ACTION_POINTER_UP:
if (event.getPointerCount() == 2) {
isScaling = false;
}
break;
case MotionEvent.ACTION_UP:
isDragging = false;
isScaling = false;
break;
}
return true;
}
private float getDistance(MotionEvent event) {
float dx = event.getX(0) - event.getX(1);
float dy = event.getY(0) - event.getY(1);
return (float) Math.sqrt(dx * dx + dy * dy);
}
}