【问题标题】:Set ImageView Drawable to PaintDrawable - Android将 ImageView Drawable 设置为 PaintDrawable - Android
【发布时间】:2017-09-26 21:54:44
【问题描述】:

我想将我的 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 轻松完成]) .

如果有人有任何指导/建议,将不胜感激!太棒了!

【问题讨论】:

    标签: android imageview android-imageview android-drawable


    【解决方案1】:

    如果需要静态解决方案,可以在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);
    

    【讨论】:

    • 我希望它最终是动态的,硬编码的颜色只是为了测试。对不起老兄:/
    【解决方案2】:

    我是个呆子。我只需要将 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多