1

I like to create a rectangle that can randomly choose between two colors, either blur or yellow, but how do i give it the choice while creating the rectangle?

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);
jle
  • 686
  • 1
  • 8
  • 24

1 Answers1

1

You could use a random number generator. Since you only have two choices, blue or yellow, you could use a random boolean. Let's say TRUE-> Blue, and FALSE-> Yellow.

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);
emhomm4
  • 212
  • 1
  • 9
  • Can i just amplify it in case i want to have more choices, or do i need to do it in a complete different way then? – jle Nov 03 '16 at 00:17
  • It depends if you want a random color from a set list of colors, or if you want a random color out of a huge list of colors. If it's the former, you could simply generate a random number within that range (say.. 1-5) and have a case structure to assign a color to a number. If you want to do random colors, see this thread: http://stackoverflow.com/questions/4246351/creating-random-colour-in-java – emhomm4 Nov 03 '16 at 15:54
  • Can you also tell me how i get the rectangle in the centre of the screen? Do i need to calculate it or can i just set it in the center? – jle Nov 03 '16 at 22:49
  • I am assuming you will be setting the rectangle to an ImageView? If so, you center it in the xml code by doing [code](android:layout_centerInParent) – emhomm4 Nov 04 '16 at 15:34
  • Sorry that formatted weird. It's just: android:layout_centerInParent – emhomm4 Nov 04 '16 at 15:35
  • No, it's not an imageview. Is there any way to center it programmatically? – jle Nov 04 '16 at 17:14
  • How can i set it to an imageView in case i dont generate it as an imageView? – jle Nov 04 '16 at 18:19
  • How do i set it to an ImageView afterwards? – jle Nov 08 '16 at 17:02