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;
}
}
这是我的代码
我想要的是,当我握住手指时,位图每3秒在随机位置x y中开始绘制一次。
一切正常,但是问题图像在每个位置都疯狂地绘制,我不知道该怎么做,我尝试在ACTION_DOWN上调用invalidate(),但是现在我的圈子每3秒绘制一次到我触摸的位置。
任何帮助表示赞赏。
最佳答案
我不确定我完全了解您想要什么,但是您的代码存在以下问题:onDraw
经常被调用。在每个这些调用中,您都以3秒的延迟运行r2
。如此有效,r2
的运行频率与onDraw
相同,但是第一次延迟了3秒。
我想您想做的是在单独的线程中运行r2
并每3秒不断更新位置,如下所示:
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;
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);
new Thread(r2).start(); // run r2 in a separate thread
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(touch == true){
paint.setARGB(255, 222, 78, 112);
canvas.drawBitmap(android, androidX, androidY, null);
canvas.drawCircle(x,y,radius,paint);
}
}
@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;
}
return true;
}
}