【问题标题】:Convert value between 0 and 1 to hexadecimal将 0 到 1 之间的值转换为十六进制
【发布时间】:2014-07-21 03:06:09
【问题描述】:

在我正在开发的应用程序中,我正在尝试创建一个实用程序方法。这种方法的想法是它采用 #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;
}

如何将 0 到 1 之间的 alpha 值转换为 alpha 的十六进制值,我可以在颜色 int 之前添加?

【问题讨论】:

    标签: android colors alpha hex


    【解决方案1】:
    // 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");
    }
    

    【讨论】:

      【解决方案2】:

      试试这个

      public static int colorWithAlpha(int color, float alpha) {
          return color | ((int)(alpha*255)<<24);
      }
      

      【讨论】:

        猜你喜欢
        • 2015-08-25
        • 1970-01-01
        • 1970-01-01
        • 2014-02-05
        • 2013-09-27
        • 2011-08-04
        • 2018-01-22
        • 1970-01-01
        相关资源
        最近更新 更多