I'm working on a project that allows a user to adjust the alpha of a color using a custom slider. The slider returns an integer from 0-255 that defines the new alpha value the user wishes to use.
The problem is that the colors have to be in hexadecimal, and I don't know how to convert the 0-255 integer into a hexadecimal integer that can modify the original ARGB hexadecimal. I have done a little research (Like "How would one change the alpha of a predefined hexadecimal color?"), but nothing I found could fix my problem. I thought about using the Color class from java AWT, however, it doesn't have a getRGBA() method.
/**
* Original ARGB hexadecimal
* Alpha: 255, Red: 238, Blue: 102, Green: 0
*/
int originalColor = 0xFFEE6600;
/**
* Creates a new hexadecimal ARGB color from origColor with its alpha
* replaced with the user's input (0-255)
* EX: If userInputedAlpha = 145 than the new color would be 0x91EE6600
*/
int newColor = changeAlpha(origColor, userInputedAlpha);
All I need is the changeAlpha method, which modifies the color parameter's alpha (which is a hexadecimal integer) with the user inputed alpha (which is an integer from 0-255)
You know that the alpha value is stored in the bits 24 to 31, so what you can do is to apply first a mask to drop the previous alpha value and then shift the one the user inputted to apply it to the color.
int changeAlpha(int origColor, int userInputedAlpha) {
origColor = origColor & 0x00ffffff; //drop the previous alpha value
return (userInputedAlpha << 24) | origColor; //add the one the user inputted
}
Which can be easily reduced to a one liner:
return (origColor & 0x00ffffff) | (userInputedAlpha << 24);
It seems that you were perturbed about the fact that the values are in hexadecimal or not. An integer is an integer, hexadecimal is just a notation. After all there's only 0 and 1 in our computers.