2016-08-22 31 views
1

我有XML梯度绘制资源文件在这里:设置ImageView的前景渐变色编程

文件: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设置此可绘制前景。可能吗?

+0

检查我的答案 –

回答

1

试试这个snipet:

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

img.setImageResource将取代而不是添加渐变到我的ImageView图像背景或前景,所以这是绝对错误的 –

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);