当前位置: 代码迷 >> Android >> 看一上这段代码,小弟我想用拖动这个圆,可以移动的位置一直不对,求解
  详细解决方案

看一上这段代码,小弟我想用拖动这个圆,可以移动的位置一直不对,求解

热度:22   发布时间:2016-05-01 17:45:25.0
看一下这段代码,我想用拖动这个圆,可以移动的位置一直不对,求解
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;
}
  相关解决方案