Android雷达效果

2020-07-03 11:05:41 浏览数 (1)

雷达.gif

定义一些变量
代码语言:javascript复制
    private int width, height, radius;
    private SweepGradient sweepGradient;
    private Paint paint = new Paint();
    private Matrix matrix = new Matrix();
    //递增的角度
    private int FACTOR = 2;
    private int RATIO = 0;
    //背景paint
    private Paint bgPaint = new Paint();
在onlayout中初始化参数
代码语言:javascript复制
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        width = getMeasuredWidth();
        height = getMeasuredHeight();
        radius = (int) (Math.min(width, height) / 2.0f);

        sweepGradient = new SweepGradient(radius, radius, new int[]{Color.GREEN, Color.TRANSPARENT}, null);
        paint.setShader(sweepGradient);
        paint.setAntiAlias(true);

        bgPaint.setStyle(Paint.Style.STROKE);
        bgPaint.setAntiAlias(true);
        bgPaint.setColor(Color.WHITE);
        bgPaint.setStrokeWidth(2);
        bgPaint.setPathEffect(new DashPathEffect(new float[]{10, 10}, 0));
    }
ondraw中利用使用sweepGradient 的paint画圆,并利用matrix旋转变换实现旋转
代码语言:javascript复制
    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawCircle(radius, radius, radius, paint);
        drawBackGround(canvas);

        RATIO  = FACTOR;
        if (RATIO == 360) {
            RATIO = 0;
        }
        matrix.setRotate(RATIO, radius, radius);
        sweepGradient.setLocalMatrix(matrix);
        postInvalidateDelayed(10);
    }

    /**
     * 画背景
     *
     * @param canvas
     */
    private void drawBackGround(Canvas canvas) {
        canvas.drawCircle(radius, radius, radius, bgPaint);
        canvas.drawCircle(radius, radius, radius / 4.0f, bgPaint);
        canvas.drawCircle(radius, radius, radius * 2.0f / 4.0f, bgPaint);
        canvas.drawCircle(radius, radius, radius * 3.0f / 4.0f, bgPaint);
        canvas.drawPoint(radius, radius, bgPaint);

        Path path_h = new Path();
        path_h.moveTo(0, radius);
        path_h.lineTo(radius * 2, radius);
        canvas.drawPath(path_h, bgPaint);

        Path path_v = new Path();
        path_v.moveTo(radius, 0);
        path_v.lineTo(radius, radius * 2);
        canvas.drawPath(path_v, bgPaint);
    }
项目地址:https://gitee.com/aruba/ShaderApplication.git

0 人点赞