Generate a circle randomly on the screen and make

2019-03-02 17:56发布

问题:

So ive been trying to make a game app that either displays a red button with text or a green button with text randomly on the android screen. If anyone can help me with this i would appreciate it. also on a side note i want to slowly generate faster cool upside if anyone knows how to do that. Thanks!

@SuppressLint("DrawAllocation")
@Override
protected void onDraw(Canvas canvas){

    String str = "Joke of the day";
    super.onDraw(canvas);
    paint = new Paint();
    Random random = new Random();
    Random randomTwo = new Random();

    //Rect ourRect = new Rect();
    Rect topRect = new Rect();
    Rect backGround = new Rect();

    paint.setColor(Color.BLACK);
    backGround.set(0,0,canvas.getWidth(),canvas.getHeight());
    canvas.drawRect(backGround, paint);
    for(int i = 0; i <= 900; i++;){

    }

    if(blank == time){
        paint.setColor(Color.RED);
        canvas.drawCircle(random, randomTwo, 230, paint);
    }else {
        paint.setColor(Color.GREEN);
        canvas.drawCircle(random, randomTwo, 230, paint);
    }
}

回答1:

You only need one Random instance.

Declare private long lastUpdated = 0; and private int lastColor = Color.BLACK; outside of the onDraw.

Update the bottom portion to:

final float radius = 230f;
if(System.currentTimeMillis() > lastUpdated + 1000){
    lastColor = random.nextInt(2) == 1 ? Color.RED : Color.GREEN;
    lastUpdated = System.currentTimeMillis();
}
paint.setColor(lastColor);
canvas.drawCircle(random.nextInt(canvas.getWidth()-radius/2) + radius/2f, random.nextInt(canvas.getHeight()-radius/2) + radius/2f, radius, paint);

This will draw a circle of either red or green at random location every second.

You need the radius/2 because the coordinates are from the center of the circle.

As for your second part of your question, also on a side note i want to slowly generate faster cool upside. You'd have to clarify what you mean.

Edit: Provided a more complete (and correct) sample here: https://gist.github.com/mshi/8287fd3956c9a917440d