Android颜色渐变(gradient)实现

XML

shape_gradient.xml

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:angle="-90"
android:startColor="@color/colorPrimaryDark"
android:endColor="@color/colorPrimary"
/>
</shape>

LinearGradient

1
2
3
4
5
6
7
8
9
10
11
/**
@param x0 起点X坐标
@param y0 起点Y坐标
@param x1 终点X坐标
@param y1 终点Y坐标
@param colors 所有颜色渐变集合
@param positions 可以设置均匀渐变,也可以按照自定义比例进行渐变,还可以为null。假设1为整个渐变的长度,我们设置的所有颜色(假设有4种颜色),都以同等的权重(渐变长度比例0.25:0.25:0.25:0.25)进行颜色渐变。
@param tile 着色器的不同模式
*/
public LinearGradient(float x0, float y0, float x1, float y1, int colors[], float positions[],
TileMode tile)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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);
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//获取View的宽高
int width = getWidth();
int height = getHeight();

int colorStart = getResources().getColor(R.color.colorStart);
int colorCenter = getResources().getColor(R.color.colorCenter);
int colorEnd = getResources().getColor(R.color.colorEnd);

Paint paint = new Paint();
LinearGradient backGradient = new LinearGradient(0, 0, 0, height, new int[]{colorStart, colorCenter ,colorEnd}, null, Shader.TileMode.CLAMP);
paint.setShader(backGradient);
canvas.drawRect(0, 0, width, height, paint);
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :