background
When doing page development at ordinary times, it is often encountered that UI design draws a line of text, and then gives a color value like #565D66, and then gives a transparency of 80%. And then you look at it and you say: What a nuisance, can’t you give me a color value that I can use directly? Then began to in-depth communication with UI teacher.
General implementation
Then you passed Baidu, found a hexadecimal color value comparison table, silently added two transparency, and then encountered a TextView, and then searched the table, silently modified the color value…… The mood is not very beautiful
Enlarge recruit
First of all, let’s explain the meaning of the face value in Android
Color values in Android usually follow the RGB/ARGB standard and are usually used in hexadecimal format, beginning with a # character.
#FF00CC99 #FF00CC99 #FF00CC99 #FF00CC99 #FF00CC99 99 is the blue value
The code:
*/ fun colorAlphaConvert(alpha: Float, color: Int): object AlphaConvertUtil {/** * colorAlphaConvert(alpha: Float, color: Int): Int {// calculate the transparency value based on the percentage val alphaInt: Int = (alpha * 0xff).toint () val alphaFinal = alphaInt SHL 24 or 0x00FFFFFF return color and alphaFinal} /** * colorAlphaConvert(alpha: Float, textView: textView) {// calculate the value of transparency based on the percentage val alphaInt: Int = (alpha * 0xff).toint () val alphaFinal = alphaInt SHL 24 or 0x00FFFFFF val color = textView.currentTextColor textView.setTextColor(color and alphaFinal) } }Copy the code
The principle of interpretation
We do the conversion in code
- First by textView. CurrentTextColor to view directly set color values
- The first two digits represent transparency, and the actual transparency value is calculated as a percentage
For example, 80% transparency 0.8 * 0xff = 0xcc 3. Shift 0xcc 24 bits to the left to get 0xcc000000, then or with 0x00FFFFFF to get 0xccFFFFFF 4. Finally, the result of the previous step and the real color value and operation, modify the first two, get the final color value, and then set it
core idea
Get the current color value, manually convert the first two opacity, and then in the Settings. In order to improve the efficiency of the conversion of some bit operations