public class MyGameView extends View implements OnTouchListener{
static int x, y;
final static int radius = 25;
private int androidX;
private int androidY;
Paint paint;
Bitmap android;
boolean touch = false;
Handler handler = new Handler();
private Runnable r = new Runnable() {
@Override
public void run() {
invalidate();
}
};
private Runnable r2 = new Runnable() {
@Override
public void run() {
androidX = (int) Math.ceil(Math.random() * (MyGameView.this.getWidth()-android.getWidth()));
androidY = (int) Math.ceil(Math.random() * (MyGameView.this.getHeight()-android.getHeight()));
}
};
public MyGameView(Context context) {
super(context);
paint = new Paint();
paint.setAntiAlias(true); // smooth rendering
android = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
setFocusable(true);
setOnTouchListener(this);
}
@Override
protected void onDraw(Canvas canvas) {
if(touch == true){
paint.setARGB(255, 222, 78, 112);
canvas.drawBitmap(android, androidX, androidY, null);
canvas.drawCircle(x,y,radius,paint);
}
handler.postDelayed(r, 1000);
handler.postDelayed(r2, 3000);
super.onDraw(canvas);
}
@Override
public boolean onTouch(View view, MotionEvent event) {
x=(int)event.getX()-(radius/2);
y=(int)event.getY()-(radius/2);
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
touch = true;
break;
case MotionEvent.ACTION_UP:
touch = false;
break;
}
invalidate();
return true;
}
}
这是我的代码我想要的是当我握住手指时,位图开始在随机位置 x y 处每 3 秒绘制一次。一切正常,但问题图像疯狂地绘制到每个位置,我不知道该怎么做,我尝试在 ACTION_DOWN 上调用 invalidate() 但现在我的圆圈每 3 秒绘制一次到我触摸的位置。任何帮助表示赞赏。