官方的定义是这样的:
Shader是返回水平跨度颜色的对象的基类,绘图期间。 Shader的子类安装在Paint调用中,paint.setShader(着色器)。 之后的任何对象(除了位图之外)都是使用该绘制绘制将从着色器获取其颜色。
/**
*创建一个沿线绘制线性渐变的着色器。
*
* @param x0渐变线起点的x坐标
* @param y0渐变线起点的y坐标
* @param x1渐变线末端的x坐标
* @param y1渐变线末端的y坐标
* @param colors要沿渐变线分布的颜色
* @param position可能为null。 相对位置[0..1]
*颜色数组中的每个对应颜色。 如果为null,
*颜色沿梯度线均匀分布。
* @param tile Shader平铺模式
*/
public LinearGradient(float x0, float y0, float x1, float y1, @NonNull @ColorInt int colors[],
@Nullable float positions[], @NonNull TileMode tile) {
if (colors.length < 2) {
throw new IllegalArgumentException("needs >= 2 number of colors");
}
if (positions != null && colors.length != positions.length) {
throw new IllegalArgumentException("color and position arrays must be of equal length");
}
mType = TYPE_COLORS_AND_POSITIONS;
mX0 = x0;
mY0 = y0;
mX1 = x1;
mY1 = y1;
mColors = colors.clone();
mPositions = positions != null ? positions.clone() : null;
mTileMode = tile;
}
/**
*创建一个沿线绘制线性渐变的着色器。
*
* @param x0渐变线起点的x坐标
* @param y0渐变线起点的y坐标
* @param x1渐变线末端的x坐标
* @param y1渐变线末端的y坐标
* @param color0渐变线开头的颜色。
* @param color1渐变线末尾的颜色。
* @param tile Shader平铺模式
*/
public LinearGradient(float x0, float y0, float x1, float y1,
@ColorInt int color0, @ColorInt int color1,
@NonNull TileMode tile) {
mType = TYPE_COLOR_START_AND_COLOR_END;
mX0 = x0;
mY0 = y0;
mX1 = x1;
mY1 = y1;
mColor0 = color0;
mColor1 = color1;
mColors = null;
mPositions = null;
mTileMode = tile;
}
第一种方法:能设置颜色集,放置多种色值。
第二种方法:设置两种颜色,开始和结束的颜色。
1、初始化colors集合,放置需要的颜色,然后初始化 sweepGradient,指定中心点,然后给画笔设置着色器。
int [] colors = new int[]{context.getResources().getColor(R.color.progress_color11),
context.getResources().getColor(R.color.progress_color12),
context.getResources().getColor(R.color.progress_color13),
context.getResources().getColor(R.color.progress_color14),
context.getResources().getColor(R.color.progress_color15),
context.getResources().getColor(R.color.progress_color16),
linearGradient = new LinearGradient(0, 0, width, 0, colors, null, LinearGradient.TileMode.CLAMP);
paint.setShader(linearGradient);
2、在onDraw()中,画它!
canvas.drawLine(0, 0, width, 0, paint);
描述:
/**
*如果着色器在其外部绘制,则复制边缘颜色
*原始界限
*/
效果如下:
描述:
/**
*水平和垂直重复着色器的图像
*/
效果如下:
描述:
/**
*水平和垂直重复着色器的图像,交替
*镜像使相邻图像始终接缝
*/
效果如下: