高级UI<第二十一篇>:使用SweepGradient实现雷达扫描效果

使用梯度渲染/渐变渲染(SweepGradient)可以实现雷达扫描效果,它的初始角度是0,使用矩阵变换的旋转操作可以重置SweepGradient的角度

    mSweepGradient.setLocalMatrix(matrix);
    matrix.setRotate(degree, mWidth / 2, mWidth / 2);

最后再使用

    postInvalidate();

无限重绘。

代码如下:

public class RadarView extends View {

    private Paint mPaint;
    private SweepGradient mSweepGradient;

    private Matrix matrix;

    //画笔粗细
    private int strokeWidth = 5;


    /**
     * 旋转的角度
     **/
    private int degree = 0;

    public RadarView(Context context) {
        this(context, null);
    }

    public RadarView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RadarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);


        mPaint = new Paint();
        mPaint.setAntiAlias(true);

        matrix = new Matrix();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        //将背景设置成白色
        canvas.drawColor(Color.WHITE);

        int mWidth = canvas.getWidth();
        if(mSweepGradient == null){
            mSweepGradient = new SweepGradient(mWidth / 2, mWidth / 2, new int[]{Color.TRANSPARENT, Color.CYAN}, null);
        }

        //画圆1
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(strokeWidth);
        mPaint.setColor(Color.parseColor("#e04095af"));
        canvas.drawCircle(mWidth / 2, mWidth / 2, (mWidth-strokeWidth) / 2, mPaint);

        //画圆2
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(strokeWidth);
        mPaint.setColor(Color.parseColor("#e04095af"));
        canvas.drawCircle(mWidth / 2, mWidth / 2, (mWidth-strokeWidth) / 8 * 3, mPaint);

        //画圆3
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(strokeWidth);
        mPaint.setColor(Color.parseColor("#e04095af"));
        canvas.drawCircle(mWidth / 2, mWidth / 2, (mWidth-strokeWidth) / 4, mPaint);

        //画圆4
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(strokeWidth);
        mPaint.setColor(Color.parseColor("#e04095af"));
        canvas.drawCircle(mWidth / 2, mWidth / 2, (mWidth-strokeWidth) / 8, mPaint);

        //画点
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(strokeWidth);
        canvas.drawPoint(mWidth / 2, mWidth / 2, mPaint);

        //通过梯度渲染画扫描框
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setShader(mSweepGradient);
        canvas.drawCircle(mWidth / 2, mWidth / 2, mWidth / 2, mPaint);


        //下面开始为重绘之前做准备

        //(1)重绘之前,将mPaint还原成初始状态
        mPaint.reset();

        //(2)使用Matrix旋转
        mSweepGradient.setLocalMatrix(matrix);
        matrix.setRotate(degree, mWidth / 2, mWidth / 2);
        degree++;
        if (degree > 360) {
            degree = 0;
        }
        postInvalidate();
    }
}

效果如下:

1.gif

[本章完...]

你可能感兴趣的:(高级UI<第二十一篇>:使用SweepGradient实现雷达扫描效果)