Android开发之渐变色
在android.graphics中提供了有关Gradient类,包含LinearGradient线性渐变、 RadialGradient径向渐变和SweepGradient梯度渐变三种,它们的基类为android.graphics.Shader。
1. LinearGradient 线性渐变
构造体
LinearGradient(float x0, float y0, float x1, float y1, int[] colors, float[] positions, Shader.TileMode tile)
LinearGradient(float x0, float y0, float x1, float y1, int color0, int color1, Shader.TileMode tile)
参数
说明
x0
渐变线起点的x坐标
y0
渐变线起点的y坐标
x1
渐变线末端的x坐标
y1
渐变线末端的y坐标
colors
要沿着渐变线分布的颜色数组
color0
渐变线开始处的颜色
color1
渐变线末端的颜色
positions
颜色数组中每个对应颜色的相对位置[0,1]。如果为null,则颜色沿线均匀分布。
tile
着色器平铺模式
例子如下
Paint paint =new Paint();
//两个坐标形成变量,规定了渐变的方向和间距大小,着色器为镜像
LinearGradient linearGradient =new LinearGradient(0,0,200,0, Color.RED,Color.BLUE, Shader.TileMode.MIRROR);
paint.setShader(linearGradient);
paint.setStrokeWidth(50);
canvas.drawLine(0,getMeasuredHeight()/2,getMeasuredWidth(),getMeasuredHeight()/2, paint);
LinearGradient
2. RadialGradient 径向/放射渐变
构造体
RadialGradient(float x, float y, float radius, int[] colors, float[] positions, Shader.TileMode tile)
RadialGradient(float x, float y, float radius, int color0, int color1, Shader.TileMode tile)
参数
说明
x
半径中心的x坐标
y
半径中心的y坐标
radius
必须是积极的。此渐变的圆的半径
colors
颜色分布在圆的中心和边缘之间
color0
圆圈中心的颜色
color1
圆圈边缘的颜色
positions
颜色数组中每个对应颜色的相对位置[0,1]。如果为null,则颜色沿线均匀分布。
tile
着色器平铺模式
例子如下
paint =new Paint();
radialGradient =new RadialGradient(240,360,200, new int[]{Color.BLUE, Color.GREEN, Color.RED },null, Shader.TileMode.CLAMP);
paint.setShader(radialGradient);
canvas.drawCircle(240,360,200,paint);
RadialGradient
3. SweepGradient 扫描/梯度/扇形渐变
构造体
SweepGradient(float x, float y, int[] colors, float[] positions)
SweepGradient(float x, float y, int color0, int color1)
参数
说明
x
中心的x坐标
y
中心的y坐标
colors
颜色分布在中心周围,阵列中必须至少有2种颜色。
color0
在扫描开始时使用的颜色
color1
在扫描结束时使用的颜色
positions
颜色数组中每个对应颜色的相对位置[0,1]。如果为null,则颜色沿线均匀分布。
例子
paint =new Paint();
int[] colors = new int[]{Color.GREEN, Color.GREEN, Color.BLUE, Color.RED, Color.RED};
sweepGradient = new SweepGradient(240, 360,colors,null);
paint.setShader(sweepGradient);
canvas.drawCircle(x,y,200,paint);
SweepGradient
\( ^o ^)/了解!