动态设置gradient的好处是可以设置多个颜色变化,做出更过酷炫的颜色变换。
先上效果图:
其实背景就是一个自定义View,然后在布局文件中引用进去:
public class gradientView extends View{
public gradientView(Context context) {
super(context);
}
public gradientView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public gradientView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
int color1 = getResources().getColor(R.color.orange);
int color2 = getResources().getColor(R.color.splashCenter);
int color3 = getResources().getColor(R.color.colorPrimaryDark);
int color4 = getResources().getColor(R.color.green_light);
int color5 = getResources().getColor(R.color.green);
Paint paint = new Paint();
LinearGradient gradient = new LinearGradient(0,0,0,height,new int[]{color1,color2,color3,color4,color5},null, Shader.TileMode.MIRROR);
paint.setShader(gradient);
canvas.drawRect(0,0,width,height,paint);
}
}
在布局文件中引用:
网上更多的例子可以看下这篇博客:
https://www.jianshu.com/p/32d17739d378
整个项目的下载地址:
https://github.com/buder-cp/base_component_learn