【问题标题】:Convert RadialGradient to Drawable? (CSS RadialGradient to Android)将 RadialGradient 转换为 Drawable? (CSS RadialGradient 到 Android)
【发布时间】:2023-06-09 04:50:02
【问题描述】:

我正在尝试将 CSS 径向渐变转换为 Android,并发现我需要 RadialGradient,因为 CSS 具有多种颜色和停止点。下面是 CSS 的一个示例。

background-image: radial-gradient(circle at 24% 50%, #ffffff, #c0e3e0 20%, #a4c4d7 61%, #000000);

我尝试使用

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>

<gradient
    android:centerX="36%"
    android:centerY="50%"
    android:endColor="#000000"
    android:gradientRadius="300"
    android:startColor="#ffffff"
    android:type="radial"
    />
 </shape>

但您不能包含所有颜色并且没有停止。

我选择了 RadialGradient

 RadialGradient radialGradient = new RadialGradient(0.25f, 0.45f, 140.f, new int[]{
            ContextCompat.getColor(context, R.color.background_gradient_start_color),
            ContextCompat.getColor(context, R.color.background_gradient_second_color),
            ContextCompat.getColor(context, R.color.background_gradient_third_color),
            ContextCompat.getColor(context, R.color.background_gradient_end_color)}, new float[]{1.0f, 0.2f, .61f, 1.0f},
            Shader.TileMode.CLAMP);

但我无法将 RadialGradient 设置为我的 RelativeLayout 的背景,因为它不是 android.graphics.Drawable 或不知道如何设置。有人可以提供解决方案吗?

【问题讨论】:

  • 希望您已经找到了解决方案,但如果没有,您可以参考*.com/a/2762454/2220318 我正在尝试做类似的事情,但还没有找到解决方案。我正在查看的格式是径向渐变(100% 100% at center 125%, color1 20%, color2 25%)非常感谢任何帮助:)

标签: android css radial-gradients


【解决方案1】:

你可以使用layer-list,像这样:

<?xml version="1.0" encoding="utf-8"?>
<layer-list>
    <item>
        <shape xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="rectangle">
            <gradient
                android:centerX="36%"
                android:centerY="50%"
                android:endColor="#33c0e3e0"
                android:gradientRadius="300"
                android:startColor="#ffffff"
                android:type="radial"
                />
        </shape>
    </item>
    <item>
        <shape xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="rectangle">
            <gradient
                android:centerX="36%"
                android:centerY="50%"
                android:endColor="#000000"
                android:centerColor="@color/colorAccent"
                android:gradientRadius="600"
                android:startColor="#9ca4c4d7"
                android:type="radial"
                />
        </shape>
    </item>
</layer-list>

【讨论】:

  • 这如何结合止损?