Java 以编程方式设置imageview前景渐变颜色
我这里有xml渐变可绘制资源文件: 文件:fg_graidientJava 以编程方式设置imageview前景渐变颜色,java,android,xml,android-layout,gradient,Java,Android,Xml,Android Layout,Gradient,我这里有xml渐变可绘制资源文件: 文件: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"
<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
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设置这个可绘制的前景。有可能吗?试试这个小剪刀:
ImageView img = (ImageView)findViewById(R.id.backimg);
img.setImageResource(R.drawable.fg_graidient);
以编程方式创建渐变形状
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);
使用
setImageResource将替换我的imageview,而不是向图像背景或前景添加渐变,因此这是绝对错误的
Button btn= (Button)findViewById(R.id.btn);
btn.setBackgroundDrawable((Drawable)p);