自定义View之雷达图

作者: Jack921 | 来源:发表于2018-08-09 13:51 被阅读159次

    好久没有写过自定义的文章,这次重拾这方面的内容,从雷达图开始。首先看一下效果图:


    效果图.gif

    这就是大概的效果图了,下面我们就一一讲解吧。

    首先为了看的懂,我会把所以变量贴出来,以防止看代码段的时候大家不知其意思:

    private Paint mBroadPaint = new Paint();//边
    private Paint mMarkEasePaint = new Paint();//数值面积
    private Paint mMarkPaint = new Paint();//数值边
    private Paint mCircleHoldPaint = new Paint();//各个数值点
    private Paint mDrawTextPaint = new Paint();//各个角文字
    private Paint mHoldTextPaint = new Paint();//数值点文字
    private Paint mIntervalTextPaint = new Paint();//区间点
    
    public static final double CIRCLE_ANGLE = 2 * Math.PI;
    private int broad_color = Color.parseColor("#585858");//边的颜色
    private int broad_color_text = Color.parseColor("#88001B");//角的字体颜色
    private int mark_color = Color.parseColor("#FDECA6");//数值区域颜色
    private int mark_broad_color = Color.parseColor("#FFCA18");//数值边的颜色
    private int corner_hold_color = Color.parseColor("#EC1C24");//数组提示字体的颜色
    private int circle_hold_color = Color.parseColor("#008B8B");//数值区域点的颜色
    private int interval_text_color = Color.parseColor("#2F4F4F");//区间点的颜色
    
    private float mBroadStrokeWidth = 1.5f;//边的粗细
    private float mMarkBroadStrokeWidth = 1.5f;//数值区域边的粗细
    private int corner_textSize;//边角的字体的大小
    private int circle_hold_textSize;//数组提示字体的大小
    private int mMarkEaseAlpha = 70;//数值区域的透明度
    private int mBroadAlpha = 225;//各个边的连线的透明度
    private int mIntervalTextSize;//区间点的大小
    
    private List<String> cornerName = new ArrayList<>();//角的名字的集合
    private List<Float> listData = new ArrayList<>();
    private int angleStatus = 0;//角的状态
    private float maxValue = 0f;//最大值
    private Float radius = 0f;//画图的半径
    
    private float[] listAngle;//所有角的集合
    private boolean drawText = false;//画不画数组提示
    private long duration = 3000;//动画时间
    private boolean openDuration = true;//是否开启动画
    private boolean openDataEasePoint = true;//是否开启区域数值提示
    
    private int marginNum = 4; //画多少个雷达图的边
    private float margin; //每个雷达图边的间隔
    
    private double mPerimeter;
    private float mFlingPoint;
    
    private GestureDetector mDetector;
    private Scroller scroller;
    

    接着就是自定义确定整个View的大小,代码如下:

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthModel = MeasureSpec.getMode(widthMeasureSpec);
        int heightModel = MeasureSpec.getMode(heightMeasureSpec);
        int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
        int measureHeight = MeasureSpec.getSize(heightMeasureSpec);
        int width;
        int height;
        if (widthModel == MeasureSpec.EXACTLY) {
            width = measureWidth;
        } else {
            width = getPaddingLeft() + getPaddingRight() + measureWidth;
        }
        if (heightModel == MeasureSpec.EXACTLY) {
            height = measureHeight;
        } else {
            height = (getPaddingTop() + getPaddingBottom() + measureHeight) / 2;
        }
        setMeasuredDimension(width, height);
    }
    
    @Override
    protected void onSizeChanged(int width, int height, int oldw, int oldh) {
        super.onSizeChanged(width, height, oldw, oldh);
        radius = (float) Math.min(width, height) / 3;
        margin = radius / 4;
        mPerimeter = 2 * Math.PI * radius;
        float tempRedius = (float) 360 / listData.size();
        listAngle = new float[listData.size()];
        for (int i = 0; i < listData.size(); i++) {
            listAngle[i] = tempRedius * (i + 1);
        }
        if (this.openDuration) {
            loadStartAnimator();
        }
    }
    

    当MeasureSpec.getMode不等于 MeasureSpec.EXACTLY时即父控件没有指定大小时,该View的宽时这个屏幕的宽再加它的左右间隔,而高是该屏幕的高再加上下间隔再除于2,否侧就是用指定控件的大小。

    而onSizeChanged当view的大小发生变化时触发再onDraw()之前触发,所以我在这里计算出雷达图的半径(radius),和根据传进来的值计算出各个角的角度数组(listAngle),和各个雷达边的间隔(margin),主要就是这些了。

    接下来就是分析最重要的onDraw()方法,代码如下:

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (listAngle.length == 0) {
            return;
        }
        canvas.translate(getWidth() / 2, getHeight() / 2);
        canvas.rotate(180);
        canvas.save();
        //画雷达图各个边
        for (int i = 1; i <= marginNum; i++) {
            drawRadarBroad(canvas, margin * i);
        }
        //画雷达图各个边的连线
        drawPointLine(canvas, radius);
        //画雷达图的角的文字
        drawText(canvas, radius);
        //画出数值区域
        drawData(canvas, radius);
        //画出各个点
        circleHoldPaint(canvas, radius);
        //画各个区间数值提示
        drawDataEasePoint(canvas);
    }
    

    在这里我们把Canvas的原点移到这个View的中心,旋转180度为了保持刚开始时第一个点在正上方,再保存此时Canvas的状态,接着我们就要“画画”了。

    drawRadarBroad(Canvas canvas, float radius)
    public void drawRadarBroad(Canvas canvas, float radius) {
        Path path = new Path();
        for (int i = 0; i < listAngle.length; i++) {
            float[] temp = getAngle(radius, listAngle[i]);
            if (i == 0) {
                path.moveTo(temp[0], temp[1]);
            } else {
                path.lineTo(temp[0], temp[1]);
            }
        }
        float[] lastPoint = getAngle(radius, listAngle[0]);
        path.lineTo(lastPoint[0], lastPoint[1]);
        mBroadPaint.setAlpha(mBroadAlpha);
        canvas.drawPath(path, mBroadPaint);
    }
    
    public float[] getAngle(float radius, float angle) {
        float[] param = new float[2];
        param[0] = (float) Math.sin(Math.toRadians(angle)) * radius;
        param[1] = (float) Math.cos(Math.toRadians(angle)) * radius;
        return param;
    }
    
    

    我们通过margin * i计算出每个雷达边的外接圆的半径,在创建Path然后遍历各个角,通过getAngle()方法计算出各个点坐标,getAngle()里面的代码说白了只是三角计算公式而已。当它在第一个点的时候移动path即moveTo(),其后的点都是用lineTo()代表连接,然后最后一个点再和第一个点相连,形成一个闭环,最后调用Canvas.drawPath()画出这个雷达边,多次调用即画出多个边了。效果如下:


    雷达边.png
    drawPointLine(Canvas canvas, float radius)

    接下来要把上面的边连起来形成真正的雷达图,代码如下:

    public void drawPointLine(Canvas canvas, float radius) {
        for (int i = 0; i < listAngle.length; i++) {
            Path path = new Path();
            path.moveTo(0, 0);
            float[] temp = getAngle(radius, listAngle[i]);
            path.lineTo(temp[0], temp[1]);
            mBroadPaint.setAlpha(mBroadAlpha);
            canvas.drawPath(path, mBroadPaint);
        }
    }
    

    这个很简单,拿到整个最大外接圆的半径,计算出各个角的坐标,然后用Path把他们画出原点到各个角的连线,效果图如下:


    雷达图2.png

    接着画出雷达图各个角的提示文字
    drawText(Canvas canvas, float radius)

    public void drawText(Canvas canvas, float radius) {
        if (cornerName.size() == 0) {
            return;
        }
        for (int i = 0; i < listAngle.length; i++) {
            canvas.save();
            float[] temp = getAngle(radius, listAngle[i]);
            canvas.translate(temp[0], temp[1]);
            canvas.rotate(-180);
            Rect mCenterRect=new Rect();
            mIntervalTextPaint.getTextBounds(cornerName.get(i)+"",0,cornerName.get(i).length(),mCenterRect);
            if (-0.6<((int)temp[0])&&((int)temp[0])<=0.6) {
                canvas.drawText(cornerName.get(i),0,
                            temp[1]>0?-(mCenterRect.height()/2)
                            :mCenterRect.height()*2,mDrawTextPaint);
            } else {
                canvas.drawText(cornerName.get(i),
                            temp[0]>0?-(mCenterRect.width()):(mCenterRect.width()),
                            temp[1]>0?-(mCenterRect.height()/2):mCenterRect.height(),
                            mDrawTextPaint);
            }
            canvas.restore();
        }
        
    }
    

    这个整体思路也很简单,遍历雷达图的所有角,通过getAngle()拿到所有的坐标,在通过canvas.drawText()画出角的提示,这里注意的是,mDrawTextPaint我是设置居中,因为后面还涉及手势滑动,所以当-0.6<((int)temp[0])&&((int)temp[0])<=0.6时,是上下两个点,所以X的偏移我这是为0,最上面一点偏移半个文字高度,而下面是两个。假如不是上下两个点则是正常点,X点的偏移是temp[0]>0?-(mCenterRect.width()):(mCenterRect.width()),Y点的偏移是temp[1]>0?-(mCenterRect.height()/2):mCenterRect.height()。效果图如下:


    雷达图3.png
    drawData(Canvas canvas, float radius)

    接着就是画数值占雷达图的整个区域和边,代码如下:

    public void drawData(Canvas canvas, float radius) {
        if (maxValue == 0) {
            maxValue = Collections.max(listData);
        }
        Path path = new Path();
        for (int i = 0; i < listAngle.length; i++) {
            float tempRadius = (listData.get(i) / maxValue) * radius;
            float[] tempAngle = getAngle(tempRadius, listAngle[i]);
            if (i == 0) {
                path.moveTo(tempAngle[0], tempAngle[1]);
            } else {
                path.lineTo(tempAngle[0], tempAngle[1]);
            }
        }
        path.close();
        canvas.drawPath(path, mMarkEasePaint);
        canvas.drawPath(path, mMarkPaint);
    }
    

    通过(listData.get(i)/maxValue)*radius画出不同数值对应的半径,再通过getAngle()来获取角的坐标,然后依照画画雷达边画出用path.moveTo和path.lineTo画出整个路径,再通过canvas.drawPath(path,mMarkEasePaint),canvas.drawPath(path, mMarkPaint)分别画出对应的区域和对应的边。效果图如下:


    雷达图4.png
    circleHoldPaint(Canvas canvas, float radius)

    接着画出数值点和其每个点代表的数值,代码如下:

    public void circleHoldPaint(Canvas canvas, float radius) {
            if (maxValue == 0) {
                maxValue = Collections.max(listData);
            }
            for (int i = 0; i < listAngle.length; i++) {
                float tempRadius = (listData.get(i) / maxValue) * radius;
                float[] tempAngle = getAngle(tempRadius, listAngle[i]);
                if (drawText) {
                    canvas.save();
                    canvas.translate(tempAngle[0], tempAngle[1]);
                    Rect mCenterRect=new Rect();
                    mHoldTextPaint.getTextBounds(cornerName.get(i)+"",0,cornerName.get(i).length(),mCenterRect);
                    canvas.rotate(-180);
                    canvas.drawText(listData.get(i)+"",tempAngle[0]>0?-mCenterRect.width()/2:mCenterRect.width()/2,tempAngle[1]>0?-mCenterRect.height()/2:mCenterRect.height()/2,mHoldTextPaint);
                    canvas.restore();
                }
                canvas.drawCircle(tempAngle[0], tempAngle[1], 5, mCircleHoldPaint);
            }
        }
    

    首先还是遍历所有的角度的集合,和上面一样通过(listData.get(i) / maxValue) * radius拿到半径,再通过getAngle()拿到每个角度和半径对应的坐标。通过canvas.save()保存当前状态,再通过canvas.translate()把原点移动到对应的坐标,通过canvas.drawText()画出对应的数值,在canvas.restore()来恢复原先的状态。最后通过canvas.drawCircle()画出每个数值点的中心。效果图如下:


    雷达图5.png
    drawDataEasePoint(Canvas canvas)

    最后就是画各个区间的数值提示,代码如下:

    public void drawDataEasePoint(Canvas canvas) {
        if (!openDataEasePoint && listAngle.length != 0) {
            return;
        }
        float marginData = maxValue / marginNum;
        for (int i = 1; i <= marginNum; i++) {
            float[] temp = getAngle(margin * i, listAngle[0]);
            canvas.save();
            canvas.translate(temp[0], temp[1]);
            canvas.rotate(-180);
            float data = marginData * i;
            Rect mCenterRect=new Rect();
            mIntervalTextPaint.getTextBounds(data+"",0,(data+"").length(),mCenterRect);
            canvas.drawText(data+"",0, temp[1]>0?mCenterRect.height():-mCenterRect.height(), mIntervalTextPaint);
            canvas.restore();
        }
    }
    

    首先通过maxValue/marginNum计算出每个区间真是数值之间的间隔,在遍历marginNum,通过marginData*i获取每个区间的半径,再通过getAngle()获取对应的坐标,剩下的操作思路和上面的都大同小异,保存状态,计算字体大小,再通过canvas.drawText()画出字体,然后canvas.restore()还原。最终的效果图就都出来了,如下:


    雷达图5.png

    上面虽然画出了雷达图的全部样子,可是都是静态的不能手指操作。要怎么实现呢,也很简单,重写onTouch(MotionEvent event)方法,代码如下:

    scroller = new Scroller(getContext());
    mDetector = new GestureDetector(getContext(), mGestureListener);
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mDetector.onTouchEvent(event);
        return true;
    }
    
    private GestureDetector.SimpleOnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onDown(MotionEvent e) {
            if (!scroller.isFinished()) {
                scroller.forceFinished(true);
            }
            return true;
        }
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            calculationAngle(e1.getX(), e1.getY(), e2.getX(), e2.getY(), distanceX / 5, distanceY / 5);
            postInvalidate();
            return super.onScroll(e1, e2, distanceX, distanceY);
        }
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            if (Math.abs(velocityX) > Math.abs(velocityY)) {
                mFlingPoint = e2.getX();
                scroller.fling((int) e2.getX(), 0, (int) (velocityX), 0,(int) (-50 + e2.getX()),(int) (50 + e2.getX()), 0, 0);
            } else if (Math.abs(velocityX) < Math.abs(velocityY)) {
                mFlingPoint = e2.getX();
                scroller.fling(0, (int) e2.getY(), 0, (int) (velocityY), 0, 0,
                        (int) -(50 + e2.getY()),
                        (int) (50 + e2.getY()));
            }
            return super.onFling(e1, e2, velocityX, velocityY);
        }
    };
        
    public void calculationAngle(float startX, float startY, float endX, float endY, float distanceX, float distanceY) {
        float tempRadius = 0;
        int action = detectDicr(startX, startY, endX, endY);
        if (action == 1 || action == 2) {//上下
            if (startX > (getWidth() / 2)) {
                tempRadius = distanceY; //右
            } else {
                tempRadius = -distanceY;//左
            }
        } else if (action == 3 || action == 4) {//左右
            if (startY > (getHeight() / 2)) {
                tempRadius = -distanceX;//下
            } else {
                tempRadius = distanceX;//上
            }
        }
        if (tempRadius > 0) {
            angleStatus = 0;
        } else {
            angleStatus = 1;
        }
        for (int i = 0; i < listAngle.length; i++) {
            listAngle[i] += (tempRadius);
        }
    }    
        
    //通过手势来移动方块:1,2,3,4对应上下左右
    private int detectDicr(float start_x, float start_y, float end_x, float end_y) {
        boolean isLeftOrRight = Math.abs(start_x - end_x) > Math.abs(start_y - end_y) ? true : false;
        if (isLeftOrRight) {
            if (start_x - end_x > 0) {
                return 3;
            } else if (start_x - end_x < 0) {
                return 4;
            }
        } else {
            if (start_y - end_y > 0) {
                return 1;
            } else if (start_y - end_y < 0) {
                return 2;
            }
        }
        return 0;
    }    
        
    

    当我们手指在这个View滑动时,就是回调onScroll()方法,然后调用calculationAngle()方法,在这方法里detectDicr()方法是用来判断方向的,当它在上下滑石,我们用onScroll()回调的distanceY,左右就用distanceX方法,然后在根据它在哪个象限来判断正负值。再通过遍历所有角度来修改所有角度值,最后通过postInvalidate()不断刷新界面。

    当我们手指快速一滑时,会回调onFling()方法,当Math.abs(velocityX) > Math.abs(velocityY)是左右快速滑动,否则是上下快速滑动,然后在调用scroller.fling()方法让它实现平顺的滑动一段距离,然后待会回调如下方法:

    @Override
    public void computeScroll() {
        if (scroller.computeScrollOffset()) {
            int x = scroller.getCurrX();
            int y = scroller.getCurrY();
            double tempRadius = 0;
            int max = Math.max(Math.abs(x), Math.abs(y));
            double rotateDis = CIRCLE_ANGLE * (Math.abs(max - mFlingPoint) / mPerimeter);
            if (angleStatus == 0) {
                tempRadius = rotateDis;
            } else if (angleStatus == 1) {
                tempRadius = -rotateDis;
            }
            for (int i = 0; i < listAngle.length; i++) {
                listAngle[i] += (tempRadius);
            }
            postInvalidate();
        }
    }
    

    获取当前X值和Y值,比较拿到最大值,再通过Math.abs(max - mFlingPoint)/radius算出大概的角度值,angleStatus是用来判断方向的,最后还是遍历所有角,来改变所有的角度,通过postInvalidate()不断的刷新界面。这就实现了快速一滑的效果的。

    最后就是刚加载的动画了,代码如下:

    public void loadStartAnimator() {
        ValueAnimator alphaAnimator = ValueAnimator.ofInt(0, 225);
        alphaAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                mBroadAlpha = (int) valueAnimator.getAnimatedValue();
                postInvalidate();
            }
        });
        final ValueAnimator radiusAnimator = ValueAnimator.ofFloat(0, radius);
        radiusAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                radius = (Float) valueAnimator.getAnimatedValue();
                postInvalidate();
            }
        });
        final ValueAnimator marginAnimator = ValueAnimator.ofFloat(0, margin);
        marginAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                margin = (Float) valueAnimator.getAnimatedValue();
                postInvalidate();
            }
        });
        alphaAnimator.setDuration(duration);
        radiusAnimator.setDuration(duration);
        marginAnimator.setDuration(duration);
        alphaAnimator.start();
        radiusAnimator.start();
        marginAnimator.start();
    }
    

    通过ValueAnimator根据动画持续的总时间内产生多个时间因子,即mBroadAlpha(透明度),radius(半径),margin(雷达边的间距)在一段时间内不同改变,再通过postInvalidate()不断刷新界面,从而产生动画效果。

    最后奉上源码,大家有什么不懂可以看源码https://github.com/jack921/RadarView

    相关文章

      网友评论

      • d5fd115b6aac:厉害。以后项目中有自定义view找你画我赞赏如何。哈哈

      本文标题:自定义View之雷达图

      本文链接:https://www.haomeiwen.com/subject/jwbxbftx.html