简体   繁体   English

如何在Java中使用整数值修改ARGB十六进制值的alpha

[英]How to modify the alpha of an ARGB hex value using integer values in Java

I'm working on a project that allows a user to adjust the alpha of a color using a custom slider. 我正在开发一个项目,该项目允许用户使用自定义滑块调整颜色的Alpha值。 The slider returns an integer from 0-255 that defines the new alpha value the user wishes to use. 滑块返回0到255之间的整数,该整数定义用户希望使用的新alpha值。

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. 问题在于颜色必须为十六进制,并且我不知道如何将0-255整数转换为可以修改原始ARGB十六进制的十六进制整数。 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. 我做了一些研究(例如“ 如何更改预定义的十六进制颜色的alpha? ”),但是我发现没有任何东西可以解决我的问题。 I thought about using the Color class from java AWT, however, it doesn't have a getRGBA() method. 我考虑过使用Java AWT中的Color类,但是它没有getRGBA()方法。

What I want to happen: 我想发生的事情:

    /** 
     * 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) 我需要的是changeAlpha方法,该方法使用用户输入的alpha(0到255之间的整数)修改color参数的alpha(这是一个十六进制整数)。

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. 您知道alpha值存储在第24到31位中,因此您可以执行的操作是首先应用蒙版以删除先前的alpha值,然后再移动用户输入的值以将其应用于颜色。

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. 毕竟,我们的计算机中只有0和1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM