在项目中会用到颜色渐变,我们通过XML实现
创建xml文件
在drawable文件夹下创建shape资源:
shape_gradient.xml
注:
[shape] 根标签,声明一个shape
[gradient] 声明该shape的属性-渐变色,除此外还有其他属性如corners、stroke、size等等
[android:angle]渐变色的角度,举例来说,0代表从上至下颜色渐变;45代表从左至右颜色渐变;90代表从下至上颜色渐变…
[android:startColor&android:endColor] 很好理解,渐变开始的颜色和渐变结束时的颜色(从什么颜色变到什么颜色)
自定义View
MyView.java
public class MyView extends View {
public MyView(Context context) {
super(context);
}
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//获取View的宽高
int width = getWidth();
int height = getHeight();
int colorStart = getResources().getColor(R.color.red);
int color1 = Color.GRAY;
int colorEnd = getResources().getColor(R.color.star_yellow);
Paint paint = new Paint();
LinearGradient backGradient = new LinearGradient(0, 0, 0, height, new int[]{colorStart, color1, colorEnd}, null, Shader.TileMode.CLAMP);
paint.setShader(backGradient);
canvas.drawRect(0, 0, width, height, paint);
}
}
使用在xml中: