Android原生绘图(十):SweepGradient扫描渐变

1,877 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

1.简介

SweepGradient可以实现扫描渐变渲染,类似雷达扫描图,渐变圆弧,渐变进度条等,构造函数有两个

/**
 * 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[]);
/**
 * 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 color0   The color to use at the start of the sweep
 * @param color1   The color to use at the end of the sweep
 */
public SweepGradient(float cx, float cy, @ColorInt int color0, @ColorInt int color1) ;

参数说明:
cx,cy 渐变中心坐标。
color0,color1:渐变开始结束颜色。
colors,positions:类似LinearGradient,用于多颜色渐变,positions为null时,根据颜色线性渐变。

2.两种颜色渐变

构造函数:
SweepGradient(float cx, float cy, @ColorInt int color0, @ColorInt int color1)

SweepGradient sweepGradient1 = new SweepGradient(400, 400, Color.RED, Color.GREEN);
mPaint.setShader(sweepGradient1);
canvas.drawCircle(400, 400, 200, mPaint);

3.多颜色扫描渐变

构造函数:
SweepGradient(float cx, float cy,@NonNull @ColorInt int colors[], @Nullable float positions[])

int[] colors = {Color.BLUE, Color.RED, Color.YELLOW};
SweepGradient sweepGradient2 = new SweepGradient(400, 800, colors, null);
mPaint.setShader(sweepGradient2);
canvas.drawCircle(400, 800, 200, mPaint);

设置position:

position数组设置主要作用是特定位置对应颜色数组,位置取值【0-1】,0表示开始位置,1表示结束位置,数组和颜色数组一一对应。

int[] colors = {Color.BLUE, Color.RED, Color.YELLOW, Color.GREEN};
float[] positions = {0f, 0.2f, 0.6f, 1.0f};
SweepGradient sweepGradient2 = new SweepGradient(400, 400, colors, positions);
mPaint.setShader(sweepGradient2);
canvas.drawCircle(400, 400, 200, mPaint);

\