Wednesday 8 May 2013

Java Color - RGB to Hex


Wow I have had fun today.

I wanted to random generate RGB colors and then convert them to Hex.

I could not use the random generated Red Green Blue colors directly to form a Hex color as the generated numbers could be 1,2,3 characters long. 

It took me a good while with lots of reading an experimentation.

First create int variables that will random each Red Green Blue value.
int red = (int) (( Math.random()*255)+1);
int green = (int) (( Math.random()*255)+1);
int blue = (int) (( Math.random()*255)+1);

Instantiate an instance of Color that will uses the random generated Red Green Blue color ints.
Color RandomC = new Color(red,green,blue);

Create an int that will get the RGB values from the color.
int RandomRGB = (RandomC.getRGB());

Create a String that will convert RandomC RGB values to a HexString.
String RandomRGB2Hex = Integer.toHexString(RandomRGB);

Create an int variable that will convert the HexString to a HashCode.
int EndRGB = RandomRGB2Hex.hashCode();

And now you have a random generated HexCode.

Quite  a few steps, and no doubt within 10 min of posting this I will find a much easier and quicker way.

But for now I am happy that this flow works.

No comments:

Post a Comment