首页 > 解决方案 > 如何将 alpha 通道添加到 xml 中的现有 Android 颜色

问题描述

我有以下颜色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>

这可能吗?

标签: androidandroid-resourcesandroid-color

解决方案


您必须在代码中执行此操作。你可以得到这样的颜色,

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);

现在您可以使用所需的任何 alpha 重新创建颜色:

color = Color.argb(<new alpha>, r, g, b);

这当然意味着您需要从代码中构建您的可绘制对象。不干净但可能。


推荐阅读