android - 使用随机颜色绘制形状

时间:2016-11-02 19:34:30

标签: java android

我喜欢创建一个可以在两种颜色之间随机选择的矩形,无论是模糊还是黄色,但是如何在创建矩形时给它选择?

private Paint paint = new Paint();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);    
    Bitmap bg = Bitmap.createBitmap(480, 800, Bitmap.Config.ARGB_8888); 
    Canvas canvas = new Canvas (bg);  
    paint.setAntiAlias(true);
    paint.setColor(Color.BLUE);
    paint.setColor(Color.YELLOW);
    canvas.drawRect(50, 50, 200, 200, paint);

1 个答案:

答案 0 :(得分:1)

您可以使用随机数生成器。由于您只有两个选项,蓝色或黄色,您可以使用随机布尔值。让我们说TRUE->蓝色,和FALSE->黄色。

private Paint paint = new Paint();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);    
    Bitmap bg = Bitmap.createBitmap(480, 800, Bitmap.Config.ARGB_8888); 
    Canvas canvas = new Canvas (bg);  
    paint.setAntiAlias(true);

    Random randomNum = new Random();
    boolean value = randomNum.nextBoolean();

    if(value){
        paint.setColor(Color.BLUE);
    }
    else{ paint.setColor(Color.YELLOW);}

    canvas.drawRect(50, 50, 200, 200, paint);