colorballs 是一个有两个位图的类(此处未显示),我正在努力寻找是否将位图拖放到屏幕上的“正方形”(请参阅下面的“绘制方法”)中。然后位图不应该再被拖动,如果相同的位图移动到其他任何地方但不在正方形内,当我停止移动位图时它应该恢复到原始位置。请帮助代码。
// the method that draws the balls
@Override protected void onDraw(Canvas canvas) {
//canvas.drawColor(0xFFCCCCCC); //if you want another background color
//draw the balls on the canvas
for (ColorBall ball : colorballs) {
canvas.drawBitmap(ball.getBitmap(), ball.getX(), ball.getY(), null);
}
// draw the square.
Paint rectPaint = new Paint();
// color of the border
rectPaint.setColor(Color.BLUE);
rectPaint.setStrokeWidth(1);
rectPaint.setStyle(Paint.Style.STROKE);
int w = this.getWidth(), h = this.getHeight();
int offset = (h - w)/2;
int step =w/3;
rect= new Rect (0, offset+0*step, step, offset+step*1);
canvas.drawRect(rect, rectPaint);
}
// events when touching the screen
public boolean onTouchEvent(MotionEvent event) {
int eventaction = event.getAction();
int X = (int)event.getX();
int Y = (int)event.getY();
ballTouchedFlag =false;
switch (eventaction ) {
case MotionEvent.ACTION_DOWN: // touch down so check if the finger is on a ball
balID = 0;
for (ColorBall ball : colorballs) {
// check if inside the bounds of the ball (circle)
// get the center for the ball
int centerX = ball.getX() + 25;
int centerY = ball.getY() + 25;
// calculate the radius from the touch to the center of the ball
double radCircle = Math.sqrt( (double) (((centerX-X)*(centerX-X)) + (centerY-Y)*(centerY-Y)));
// if the radius is smaller then 23 (radius of a ball is 22), then it must be on the ball
if (radCircle < 23){
balID = ball.getID();
initPoint.x=X;
initPoint.y=Y;
ballTouchedFlag =true;
break;
}
}
break;
case MotionEvent.ACTION_MOVE: // touch drag with the ball
// move the balls the same as the finger
if (balID > 0 ) {
colorballs[balID-1].setX(X-25);
colorballs[balID-1].setY(Y-25);
}
break;
case MotionEvent.ACTION_UP:
// touch drop - just do things here after dropping
// Determine if the ball is touched.
break;
}
// redraw the canvas
invalidate();
return true;
}