我想将我的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;
}
但没有出现渐变。
我也看到了这一点:Imageview set color filter to gradient
但是我认为必须有一个更简单的解决方案(加上它需要一个位图src,我只想让我的ImageView成为一个带圆角的矩形[可以用PaintDrawable轻松完成])
如果有人有任何指导/建议,我们将不胜感激! TY!
答案 0 :(得分:0)
如果您需要静态解决方案,可以在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>
爪哇
ImageView imageView = (ImageView) findViewById(R.id.imageViewGradient);
imageView.setImageResource(R.drawable.gradient_1);
答案 1 :(得分:0)
我是个贬低者。我只需要将ImageView切换到普通视图,然后我就可以将drawable的背景替换为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;
}