Manual Radarview Android Radar chart (spider web)

Source: Internet
Author: User
Tags cos drawtext getcolor sin radar

The company's products need a radar chart to show the proportion of each dimension, online to find a wave, learn a lot, direct their own hands to a record

Without a picture of the void

Simple analysis of a wave, determine the radar is just a few sides-Pentagon int count=5, divided into several layers-4 layer int layercount=4

    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        drawPolygon(canvas);//画边        drawLines(canvas);//画线        drawText(canvas);//描绘文字        drawRegion(canvas);//覆盖区域    }

These are the main steps, open!

Custom Radarview Inherit view

Determine the variables that need to be used, initialize paint, calculate central angle

  Private int count = 5;//few sides     private int layercount = 4;//layer     privatefloatangle;//per bar side corresponding to central angle    private int CenterX; Center x    private int centery; Center y    Privatefloatradius; Radius     Private Paint polygonpaint; Border paint    private Paint linepaint; Wired paint    Private Paint txtpaint; Text paint    Private Paint circlepaint; Dot paint    private Paint regioncolorpaint; Coverage area paint    Private double[] percents = {0.91, 0.35, 0.12, 0.8, 0.5}; Coverage percentage     Private string[] titles = {"DotA", "Bucket Landlord", "Good luck, chicken at night", "Stone Legend", "Jump"};//text  
    Public Radarview (Context context) {This (context, NULL, 0);    } public Radarview (context context, @Nullable AttributeSet attrs) {This (context, attrs, 0); } public Radarview (context context, @Nullable attributeset attrs, int defstyleattr) {Super (context, Attrs, DefS        TYLEATTR);        Calculation central angle angle = (float) (Math.PI * 2/count);        Polygonpaint = new Paint ();        Polygonpaint.setcolor (Contextcompat.getcolor (context, r.color.radarpolygoncolor));        Polygonpaint.setantialias (TRUE);        Polygonpaint.setstyle (Paint.Style.STROKE);        Polygonpaint.setstrokewidth (4f);        Linepaint = new Paint ();        Linepaint.setcolor (Contextcompat.getcolor (context, r.color.radarlinecolor));        Linepaint.setantialias (TRUE);        Linepaint.setstyle (Paint.Style.STROKE);        Linepaint.setstrokewidth (2f);        Txtpaint = new Paint ();        Txtpaint.setcolor (Contextcompat.getcolor (context, r.color.radartxtcolor)); Txtpaint.setanTialias (TRUE);        Txtpaint.setstyle (Paint.Style.STROKE);        Txtpaint.settextsize (DENSITYUTIL.DPTOPX (context, 12));        Circlepaint = new Paint ();        Circlepaint.setcolor (Contextcompat.getcolor (context, r.color.radarcirclecolor));        Circlepaint.setantialias (TRUE);        Regioncolorpaint = new Paint ();        Regioncolorpaint.setcolor (Contextcompat.getcolor (context, r.color.radarregioncolor));        Regioncolorpaint.setstyle (Paint.Style.FILL);    Regioncolorpaint.setantialias (TRUE); }
Determine the center point

Need positive Pentagon to have a circle, the circle is connected with the positive Pentagon, in the Onsizechanged method to obtain the center, determine the radius

@Override
protected void onsizechanged (int w, int h, int oldw, int oldh) {
Super.onsizechanged (W, H, OLDW, OLDH);
Radius = Math.min (h, W)/2 * 0.7f;
CenterX = W/2;
CenterY = H/2;
}

Draw positive Pentagon

Draw positive Pentagon at the same time to depict the outermost point, determined to be divided into 4 layers, radius/layer = spacing between each layer, draw positive pentagon from the innermost layer, and the first point on each level is directly above the center point

  private void DrawPolygon (canvas canvas) {Path PATH = new Path ();        float r = radius/layercount; for (int i = 1; I <= layercount; i++) {Float CurR = R * I;//radius for current layer for (int j = 0; J < cou nt J + +) {if (j = = 0) {//per layer first point coordinate Path.moveto (CenterX, Centery-curr)                  ;                    } else {//clockwise to record the point coordinates of the remaining top corners float x = (float) (CenterX + math.sin (angle * j) * CurR);                    Float y = (float) (Centery-math.cos (Angle * j) * CurR);                Path.lineto (x, y);  }}//Outermost five dots outside the top corner (the red part of the figure) if (i = = LayerCount) {for (int j = 0; J < Count                    J + +) {float x = (float) (CenterX + math.sin (angle * j) * (CurR + 12));                    Float y = (float) (Centery-math.cos (Angle * j) * (CurR + 12)); Canvas.drawcircle (x, Y, 4, Circlepaint);            }} path.close ();        Canvas.drawpath (path, polygonpaint); }    }

Draw lines

Draw the line of the topmost top corner to the outermost vertex

  private void drawLines(Canvas canvas) {        float r = radius / layerCount;        for (int i = 0; i < count; i++) {            //起始坐标 从中心开始的话 startx=centerX , startY=centerY            float startX = (float) (centerX + Math.sin(angle * i) * r);            float startY = (float) (centerY - Math.cos(angle * i) * r);            //末端坐标            float endX = (float) (centerX + Math.sin(angle * i) * radius);            float endY = (float) (centerY - Math.cos(angle * i) * radius);            canvas.drawLine(startX, startY, endX, endY, linePaint);        }    }


At this point the simple radar shape, you can repair the correction of several sides, how many layers (continue to add text later)

    //设置几边形,**注意:设置几边形需要重新计算圆心角**    public void setCount(int count){        this.count = count;        angle = (float) (Math.PI * 2 / count);        invalidate();    }    //设置层数    public void setLayerCount(int layerCount){        this.layerCount = layerCount;        invalidate();    }

Set positive hexagon, six layers

Radarview.setcount (6);
Radarview.setlayercount (6);

For a shape, you can set the first point coordinate to the right side of the center point (centerX+curR,centerY) , calculate the remaining vertex coordinates clockwise, and x = (float) (centerX+curR*Math.cos(angle*j)), y = (float) (centerY+curR*Math.sin(angle*j)) the rest of the coordinates are changed accordingly ...

Depicting text

Because of the different product dimensions, the required radar chart style, here is only a description of the different positions of the word processing situation, the specific needs of products, depending on the product

    private void DrawText (canvas canvas) {for (int i = 0; i < count; i++) {//get to the outermost coordinates of the radar chart            float x = (float) (CenterX + math.sin (angle * i) * (RADIUS + 12));            Float y = (float) (Centery-math.cos (angle * i) * (RADIUS + 12));                if (angle * = = 0) {//The first text is located just above the top corner of Txtpaint.settextalign (Paint.Align.CENTER);                Canvas.drawtext (Titles[i], X, y-18, txtpaint);            Txtpaint.settextalign (Paint.Align.LEFT); } else if (angle * i > 0 && angle * I < MATH.PI/2) {//Fine tuning Canvas.drawtext (ti            Tles[i], x + +, Y + ten, txtpaint);                } else if (angle * I >= math.pi/2 && angle * I < Math.PI) {//The right-most text gets the length and width of the text, moving to the left by the percentage of text length                String txt = titles[i];                Rect bounds = new rect ();                Txtpaint.gettextbounds (TXT, 0, txt.length (), bounds); float height = Bounds.botTom-bounds.top;                Float width = txtpaint.measuretext (txt);            Canvas.drawtext (TXT, x-width * 0.4f, y + height +, txtpaint); } else if (angle * I >= math.pi && angle * I < 3 * MATH.PI/2) {//the same as the leftmost text gets the length and width of the text, by the length of the text                Move String txt = titles[i] than left;                Rect bounds = new rect ();                Txtpaint.gettextbounds (TXT, 0, txt.length (), bounds);                Float width = txtpaint.measuretext (txt);                float height = bounds.bottom-bounds.top;            Canvas.drawtext (TXT, x-width * 0.6f, y + height +, txtpaint);                } else if (angle * I >= 3 * math.pi/2 && angle * I < 2 * Math.PI) {//text to move left                String txt = titles[i];                Float width = txtpaint.measuretext (txt);            Canvas.drawtext (TXT, x-width-18, y + ten, txtpaint); }        }    }

Draw Coverage Area

Draws the percentage of the coverage area, percent of the line length (if the line from the center point is the percentage of the radius), where radius radius minus the interval R is the wire length

   private void drawRegion(Canvas canvas) {        Path path = new Path();        float r = radius / layerCount;//每层的间距        for (int i = 0; i < count; i++) {            if (i == 0) {                path.moveTo(centerX, (float) (centerY - r - (radius - r) * percents[i]));            } else {                float x = (float) (centerX + Math.sin(angle * i) * (percents[i] * (radius - r) + r));                float y = (float) (centerY - Math.cos(angle * i) * (percents[i] * (radius - r) + r));                path.lineTo(x, y);            }        }        path.close();        canvas.drawPath(path, regionColorPaint);    }

At this point, a simple radar chart is complete. At the same time, welcome attention to public

End

Manual Radarview Android Radar chart (spider web)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.