如何在现有的Android xml颜色中添加alpha通道

3
我在values/colors.xml中有以下颜色:
<color name="grey_1">#0F0E10</color>

我想在渐变中使用这种颜色:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="linear"
        android:angle="-90"
        android:startColor="#000F0E10"
        android:endColor="#990F0E10"/>
</shape>

然而,这样会重复RGB颜色定义。理想情况下,我希望能够像这样编写代码:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="linear"
        android:angle="-90"
        android:startColor="alpha(00, @color/grey_1)"
        android:endColor="alpha(99, @color/grey_1)"/>
</shape>

或者这个:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="linear"
        android:angle="-90"
        android:startColor="@color/grey_1"
        android:startTransparency="#00"
        android:endColor="@color/grey_1"
        android:endTransparency="#99"/>
</shape>

这是可能的吗?

2
不,这是不可能的。 :( - The Dreams Wind
5个回答

5
您可以在API 23及以上版本中使用ColorStateList来完成这个操作。
根据文档:
引用块中提到:
从API 23开始,项目可以选择定义android:alpha属性来修改基本颜色的不透明度。该属性接受一个介于0和1之间的浮点值或可解析为这种值的主题属性。通过将基本颜色的 alpha 通道乘以 alpha 值来计算项目的整体颜色。例如,以下项目代表此主题的强调色,不透明度为50%:
<item android:state_enabled="false"
      android:color="?android:attr/colorAccent"
      android:alpha="0.5" />

因此,在我的情况下,我会执行以下操作: color/gradient_start_color.xml:
<item android:color="@color/grey_1"
      android:alpha="0" />

color/gradient_end_color.xml:

<item android:color="@color/grey_1"
      android:alpha="0.6" />

drawable/gradient.xml:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="linear"
        android:angle="-90"
        android:startColor="@color/gradient_start_color"
        android:endColor="@color/gradient_end_color" />
</shape>

3

您需要在代码中实现此功能。您可以像这样获取颜色:

int color = getResources().getColor(R.color.<the color>);

你可以这样将它转换为ARGB:
int a = Color.alpha(color);
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);

现在,您可以使用任何透明度重新创建颜色:
color = Color.argb(<new alpha>, r, g, b);

这当然意味着您需要从代码中构建可绘制对象。虽然不太简洁,但仍然可行。

1
我还想指出,可以通过编程方式完成,使用ColorStateList.withAlpha()
像这样:
csl.withAlpha(0) //transparent
csl.withAlpha(255) //opaque

0
尝试使用来自androidx.core.graphics包的ColorUtils类,例如:
 int color = getResources().getColor(R.color.border_active_default);
 circle.setFillColor(ColorUtils.setAlphaComponent(color,50));

那么你就不必实现自己的定制方法了。


0

你必须设置两种不同的颜色作为起始和结束颜色。

请记住,颜色是这样定义的:#AARRGGBB表示Alpha、Red、Green和Blue。

一旦应用程序启动,资源处于只读模式。您无法以适当的方式通过编程进行更改。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接