在我正在开发的应用程序中,我正在尝试创建一个实用程序方法。这种方法的想法是它采用#RRGGBB形式的int和介于0和1之间的浮点数来描述颜色的alpha值。然后该方法应返回#AARRGGBB形式的新int。实用方法目前看起来像这样:
public static int colorWithAlpha(int color, float alpha) {
// Somehow convert alpha value between 0 and 1 to hexadecimal
return color;
}
如何将alpha的0到1之间的值转换为alpha的十六进制值,我可以将其添加到颜色int?
答案 0 :(得分:1)
试试这个
public static int colorWithAlpha(int color, float alpha) {
return color | ((int)(alpha*255)<<24);
}
答案 1 :(得分:0)
// you get the decimal value of the alpha here
int alphaInt = (int)(alpha * 255);
// check that the input color has no alpha ("left 8-bit-section" is 0)
bool colorAlreadyHasAlpha = (color & 0xff000000) == 0
if((alphaInt <= 255 || alphaInt >= 0) && !colorAlreadyHasAlpha){
// now add it to the "left 8-bit-section" of the integer
return color |= alphaInt << 24;
}
else{
throw new IllegalArgumentException("color already has alpha, or provided alpha value is invalid");
}