This site requires JavaScript, please enable it in your browser!
Greenfoot back
theDoctor
theDoctor wrote ...

2012/1/12

Generating Random Color and Brightness

theDoctor theDoctor

2012/1/12

#
This is the code I have to paint stars of a random color onto the background image. They need to have brightness as well. Any help here would be great! /** * Creates stars to be displayed on the background image. * The parameter shows the number of stars on the background image. */ public void createRandomStars(int number) { GreenfootImage background = getBackground(); for(int i = 0; i < number; i++) { int x = Greenfoot.getRandomNumber(getWidth()); int y = Greenfoot.getRandomNumber(getHeight()); GreenfootImage image = new GreenfootImage(2, 2); background.setColor(new Color(Greenfoot.getRandomNumber(255), Greenfoot.getRandomNumber(255), Greenfoot.getRandomNumber(255))); background.fillOval(Greenfoot.getRandomNumber(getWidth()), Greenfoot.getRandomNumber(getHeight()), 2, 2); } }
davmac davmac

2012/1/12

#
Brightness is not independent from the R/G/B parts of the colour. You're already picking a colour by choosing a random value for the red, green, and blue components; if the choices are all high then the colour will appear bright, if they are low it will appear dark. In other words: your spots of random colour already have random brightness.
theDoctor theDoctor

2012/1/13

#
Thanks davmac.
DonaldDuck DonaldDuck

2012/1/16

#
Just to add to this, you can assign an alpha value to your new color. The color constructor new color(float r, float g, float b, float a) does this. Greenfoot.getRandomNumber returns an int, but it should be converted to a float in the color constructor. If not, it's an easy fix. Change your color constructor to this.
background.setColor(new Color(Greenfoot.getRandomNumber(255), Greenfoot.getRandomNumber(255), Greenfoot.getRandomNumber(255), Greenfoot.getRandomNumber(255)));
You need to login to post a reply.