我知道可以通过在十六进制(#AARRGGBB)中添加Alpha通道来设置不透明度,但是如果我想使用colors.xml中不希望增加不透明度的值怎么办?

例如,我在colors.xml中使用深蓝色#074EB2,如下所示:

<color name="DarkBlue">#074EB2</color>


现在,我有一个带有边框的自定义按钮背景。我希望边框使用这种深蓝色,但是增加了不透明度。该按钮如下所示:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
    <stroke android:width="1dp" android:color="@color/DarkBlue"/>
    <corners android:radius="2dp"/>
</shape>


如何添加不透明度?我是否需要以不透明性向colors.xml添加新值?即<color name="DarkBlueTransparent">#80074EB2</color>?我看到的问题是它不可扩展-如果我在其他地方需要这种颜色80%不透明度怎么办? 90%?我想要的透明度如何,我的colors.xml文件将使用不同的值爆炸。

最佳答案

您不能在xml中进行动态不透明。但是您可以在Java端动态应用alpha。

使用此方法将Alpha应用于您的颜色。

public static int getColorWithAlpha(int yourColor, int alpha) {
    int red = Color.red(yourColor);
    int blue = Color.blue(yourColor);
    int green = Color.green(yourColor);
    return Color.argb(alpha, red, green, blue);
}


现在通过调用方法获得带有alpha的颜色

blueWithAlpha = getColorWithAlpha(darkBlue, 120);


120是您的Alpha水平


  Alpha级别应介于0到225之间


现在将颜色应用于按钮

mButton.setBackgroundColor(blueWithAlpha);

07-28 01:11
查看更多