直奔主题
/**
* A Shader that draws a sweep gradient around a center point.
*
* @param cx The x-coordinate of the center
* @param cy The y-coordinate of the center
* @param colors The colors to be distributed between around the center.
* There must be at least 2 colors in the array.
* @param positions May be NULL. The relative position of
* each corresponding color in the colors array, beginning
* with 0 and ending with 1.0. If the values are not
* monotonic, the drawing may produce unexpected results.
* If positions is NULL, then the colors are automatically
* spaced evenly.
*/
public SweepGradient(float cx, float cy,
@NonNull @ColorInt int colors[], @Nullable float positions[]) {
//..........
}
复制代码
这里我们只说第四个参数float positions[]
. 这个参数的意思是,你绘制的几种渐变色(也就是第三个参数)在绘制的圆环上的区域.注释上说这个参数可为null.如果为null,那么默认从0°开始绘制颜色,到360°结束.不管你的起始角度(>=0°)和结束角度(<=360°)是多少,都是按照这个逻辑去绘制.并且每种颜色在圆弧上是均匀分布的.
假如要绘制3种颜色,那么绘制的区域分别是0°~120°,120°~240°,240°~360°. 如果起始角度在0°~120°之间,那么圆环上会显示第一种颜色,如果起始角度超过了120°,那么圆环上就不会显示第一种颜色了,以此类推.
假如,给定一段圆弧,显示全部的渐变色,该如何去做?
设定起始角度大于0°
float startAngle
复制代码
圆弧角度小于360°
float sweepAngle
复制代码
绘制颜色
int colors[]
复制代码
既然要全部显示渐变色,那么这段圆弧就要被均分.均分后的每段圆弧的中心位置(相对于360°圆弧的位置)就是参数float positions[]
的元素.(实际测试是这样的,如有不对的,烦请指正).
那么
float divAngle = sweepAngle/colors[].length();
float start = startAngle/360;
colors[0] = start + divAngle/2;
colors[1] = start + 3 * divAngle / 2;
...
colors[n-1] = start + (2*n+1) * divAngle / 2;
复制代码
这样就ok了.