- Java code
@Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub Paint paint = new Paint(); paint.setAntiAlias(true); // 画内框外围 paint.setColor(0xAA000000); canvas.drawCircle(circleX, circleY, circleRadius, paint); super.onDraw(canvas); } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub int x = (int) event.getX(); int y = (int) event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: { offsetPoint = new Point(x, y); eventType = EVENT_MOVE; } break; case MotionEvent.ACTION_MOVE: { Log.d("TAG", "ACTION_MOVE"); if (eventType == EVENT_MOVE) { circleX += x - offsetPoint.x; circleY += y - offsetPoint.y; } } break; case MotionEvent.ACTION_UP: { eventType = EVENT_NONE; } break; } this.invalidate(); return true; }
------解决方案--------------------
int mOffsetX = 0;
int mOffsetY = 0;
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
Paint paint = new Paint();
paint.setAntiAlias(true);
// 画内框外围
paint.setColor(0xAA000000);
canvas.drawCircle(circleX + mOffsetX, circleY + mOffsetY, circleRadius, paint);
super.onDraw(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
offsetPoint = new Point(x, y);
eventType = EVENT_MOVE;
}
break;
case MotionEvent.ACTION_MOVE: {
Log.d( "TAG ", "ACTION_MOVE ");
if (eventType == EVENT_MOVE) {
moffsetX = x - offsetPoint.x;
moffsetY = y - offsetPoint.y;
}
}
break;
case MotionEvent.ACTION_UP: {
eventType = EVENT_NONE;
circleX += moffsetX;
circldY += moffsetY;
moffsetX = 0;
moffsetY = 0;
}
break;
}
this.invalidate();
return true;
}