gpt4 book ai didi

android - 如何在颜色资源上设置不透明度?

转载 作者:行者123 更新时间:2023-11-29 17:16:07 25 4
gpt4 key购买 nike

我知道我可以通过在十六进制 (#AARRGGBB) 中添加一个 alpha channel 来设置不透明度,但是如果我想使用我不想添加不透明度的 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 level should have to be between 0 to 225

现在把你的颜色应用到你的按钮上

mButton.setBackgroundColor(blueWithAlpha);

关于android - 如何在颜色资源上设置不透明度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38877863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com