将 ImageView Drawable 设置为 PaintDrawable - Android

Set ImageView Drawable to PaintDrawable - Android

我想将我的 ImageView 设置为 SweepGradient。

这是我尝试过的:

protected void onCreate(@Nullable Bundle savedInstanceState) {

    ImageView colorPicker = findViewById(R.id.color_picker);
    colorPicker.setImageDrawable(CreateColorPickerDrawable());

}

private PaintDrawable CreateColorPickerDrawable()
{
    int[] colors = {0xFFFF0000, 0xFF00FF00, 0xFF0000FF};
    PaintDrawable paintDrawable = new PaintDrawable();

    paintDrawable.setCornerRadius(getResources().getDimension(R.dimen.corner_radius));

    SweepGradient sweepGradient = new SweepGradient(50, 50, colors, null);
    paintDrawable.getPaint().setShader(sweepGradient);

    return paintDrawable;
}

但是没有出现渐变。

我也看到了这个:

但我认为必须有比这更简单的解决方案(另外它需要一个位图 src,我只希望我的 ImageView 是一个带圆角的矩形 [这可以通过 PaintDrawable 轻松完成]).

如果有人有guidance/advice,将不胜感激!泰!

如果需要静态解决方案,可以在 drawable 中使用 XML 文件。

XML (gradient_1.xml)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:startColor="#aa0000"
        android:centerColor="#00aa00"
        android:endColor="#0000aa"
        android:angle="270"/>
    <corners android:radius="0dp" />
</shape>

Java

ImageView imageView = (ImageView) findViewById(R.id.imageViewGradient);
imageView.setImageResource(R.drawable.gradient_1);

我是个笨蛋。我只需要将 ImageView 切换为普通视图,然后我就可以将可绘制的背景替换为我的 paintDrawable。

protected void onCreate(@Nullable Bundle savedInstanceState) {

View colorPicker = findViewById(R.id.color_picker);
colorPicker.setBackground(CreateColorPickerDrawable());

}

private PaintDrawable CreateColorPickerDrawable() {
int[] colors = {0xFFFF0000, 0xFF00FF00, 0xFF0000FF};
PaintDrawable paintDrawable = new PaintDrawable();

paintDrawable.setCornerRadius(getResources().getDimension(R.dimen.corner_radius));

SweepGradient sweepGradient = new SweepGradient(50, 50, colors, null);
paintDrawable.getPaint().setShader(sweepGradient);

return paintDrawable;
}