在我的应用程序中,我需要画一个圆圈,用户可以将它拖到屏幕上的任何位置。
为此,我创建了一个视图,在onDraw
方法中绘制了圆圈。我尝试使用onTouchEvent
. 但是当我尝试拖动圆圈时,圆圈并没有真正移动,而是在我触摸屏幕的任何地方创建一个新圆圈。
请有人帮我解决我所缺少的。
这是我的代码
public class Circle extends View {
Paint paint, paintSmall;
private Point start = null;
private Point cursorAtMouseDown = null;
private Point startAtMouseDown = null;
private Point endAtMouseDown = null;
private boolean movingStart = false;
private boolean movingEnd = false;
private boolean movingLine = false;
public Circle(Context context) {
super(context);
init();
}
public Circle(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public Circle(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
paint = new Paint();
start = new Point(100, 100);
paint.setColor(Color.BLUE);
paint.setStrokeWidth(10);
paint.setStyle(Paint.Style.STROKE);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setStyle(Paint.Style.STROKE);
canvas.drawCircle(start.x, start.y, 80, paint);
canvas.drawCircle(start.x, start.y, 10, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("Inside On Touch", "");
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
if (movingStart || movingEnd || movingLine) {
invalidate();
}
movingStart = false;
movingEnd = false;
movingLine = false;
break;
case MotionEvent.ACTION_OUTSIDE:
if (movingStart || movingEnd || movingLine) {
invalidate();
}
movingStart = false;
movingEnd = false;
movingLine = false;
break;
case MotionEvent.ACTION_MOVE:
Log.d("Inside On Touch", "ACTION_MOVE");
if (movingStart) {
start.x = (int) event.getX();
start.y = (int) event.getY();
invalidate();
Log.d("Inside On Touch", "--movingStart=" + movingStart);
return true;
} else if (movingEnd) {
start.x = (int) event.getX();
start.y = (int) event.getY();
invalidate();
Log.d("Inside On Touch", "--movingEnd=" + movingEnd);
return true;
} else if (movingLine) {
Log.d("Inside On Touch", "--movingLine=" + movingLine);
if (cursorAtMouseDown != null) {
// double diffX = event.getX() - cursorAtMouseDown.x;
// double diffY = event.getY() - cursorAtMouseDown.y;
// start.x = (int) (startAtMouseDown.x + diffX);
// start.y = (int) (startAtMouseDown.y + diffY);
start = cursorAtMouseDown;
invalidate();
return true;
}
}
return false;
case MotionEvent.ACTION_DOWN:
cursorAtMouseDown = new Point((int) event.getX(),
(int) event.getY());
if (cursorAtMouseDown.equals(start)) {
}
if (isCircleCenterChaged(cursorAtMouseDown)) {
movingLine = true;
}
return true;
default:
return super.onTouchEvent(event);
}
return false;
}
}