以编程方式设置imageview前景渐变颜色

时间:2016-08-22 03:51:59

标签: java android xml android-layout gradient

我这里有xml渐变可绘制资源文件:

file:fg_graidient

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
    <gradient
        android:type="linear"
        android:centerX="0%"
        android:startColor="#00020321"
        android:centerColor="#F2000000"
        android:endColor="#B2020321"
        android:angle="45"/>
</shape>

我可以像下面的imageview前景:

<ImageView
            android:id="@+id/backimg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:scaleType="fitXY"
            android:foreground="@drawable/fg_graidient"
            />

但是我想以编程方式为imageview设置这个可绘制的前景。有可能吗?

2 个答案:

答案 0 :(得分:2)

以编程方式创建渐变形状

ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
    @Override
    public Shader resize(int width, int height) {
        LinearGradient lg = new LinearGradient(0, 0, width, height,
            new int[]{Color.GREEN, Color.GREEN, Color.WHITE, Color.WHITE},
            new float[]{0,0.5f,.55f,1}, Shader.TileMode.REPEAT);
        return lg;
    }
};

PaintDrawable p=new PaintDrawable();
p.setShape(new RectShape());
p.setShaderFactory(sf);

使用

Button btn= (Button)findViewById(R.id.btn);
btn.setBackgroundDrawable((Drawable)p);

答案 1 :(得分:1)

试试这个snipet:

 ImageView img = (ImageView)findViewById(R.id.backimg);
        img.setImageResource(R.drawable.fg_graidient);