自定义多边形统计图(雷达图)

自定义雷达图 根据项目需求在图中画多条线

/**
 * 自定义多边形统计
 *
 * @author roc
 */
public class PolygonCustomeView extends View {
    int width, height;
    // 最大半径
    float maxRadius;

    // 外层点位置
    List<Point> maxPointList;

    // 边数
    int sideCount;
    // 角度
    float angle;
    // 层数
    int loopCount;

    // 绘制边的Paint
    private Paint sidePaint;
    // 绘制内容的Paint
    private Paint areaPaint;
    // 绘制文字的Paint
    private Paint textPaint;

    // private List<Float> pointValue;
    private List<List<Float>> pointValue;
    private List<String> pointName;

    public PolygonCustomeView(Context context) {
        super(context);
    }

    public PolygonCustomeView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

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

    }

    private void init(Context context, AttributeSet attrs) {
        initPaint();
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.Polygon);
        // 设置文字颜色
        setTextColor(typedArray.getColor(R.styleable.Polygon_ptitleColor, Color.BLACK));
        // 设置文字大小
        setTextSize(typedArray.getInteger(R.styleable.Polygon_titleSize, 15));
        // 设置绘制数据线的颜色
        // setAreaColor(typedArray.getColor(R.styleable.Polygon_areaColor,
        // Color.BLACK));
        // 设置边颜色
        // setSideColor(typedArray.getColor(R.styleable.Polygon_sideColor,
        // Color.BLACK));
        // 设置层数
        setLoopCount(typedArray.getInteger(R.styleable.Polygon_loopCount, 0));
        // 设置边数
        // setSideCount(typedArray.getInteger(R.styleable.Polygon_sideCount,
        // 0));
        typedArray.recycle();

    }

    private void initPaint() {
        sidePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        areaPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

        sidePaint.setStyle(Paint.Style.STROKE);

        areaPaint.setStyle(Paint.Style.STROKE);
        areaPaint.setStrokeWidth(3);

        textPaint.setStyle(Paint.Style.STROKE);
    }

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

        if (!canDraw()) {
            return;
        } else {
            canvas.translate(width / 2, height / 2);
            computeMaxPoint();
            drawPolygon(canvas);
            drawLine(canvas);
            drawArea(canvas);
            drawText(canvas);
        }

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
        maxRadius = (float) ((height / 2) * 0.8);
        postInvalidate();
    }

    /**
     * 获取外层点坐标
     */
    public void computeMaxPoint() {
        maxPointList = new ArrayList<>();

        for (int i = 0; i < sideCount; i++) {

            // 按照android的坐标系,如果不减去90度直接乘上cos的话,第一个顶点会默认在中心的右侧,
            // 而一般的认知是第一个点在正上方,所以减去90度
            float currentAngle = i * angle - 90;
            if (sideCount < 3)
                currentAngle = i * angle - 120;

            float currentX = (float) (maxRadius * Math.cos((currentAngle / 180) * Math.PI));
            float currentY = (float) (maxRadius * Math.sin((currentAngle / 180) * Math.PI));

            Point point = new Point();
            point.setX(currentX);
            point.setY(currentY);
            maxPointList.add(point);
        }
    }

    /**
     * 绘制多边形的每一层
     *
     * @param canvas
     */
    private void drawPolygon(Canvas canvas) {
        Path path = new Path();
        for (int i = loopCount; i > 0; i--) {

            if (i == loopCount) {
                if (pointName == null || pointName.size() == 0) {
                    sidePaint.setStyle(Paint.Style.STROKE);
                    sidePaint.setColor(Color.parseColor("#9f9f9f"));
                } else {
                    sidePaint.setStyle(Paint.Style.FILL);
                    sidePaint.setColor(Color.parseColor("#e5e5e5"));
                }
            } else {
                sidePaint.setStyle(Paint.Style.STROKE);
                sidePaint.setColor(Color.parseColor("#aeaeae"));
            }
            path.reset();
            float rate = computeRate(i, loopCount);
            for (int j = 0; j < sideCount; j++) {
                float currentX = maxPointList.get(j).getX() * rate;
                float currentY = maxPointList.get(j).getY() * rate;

                // 如果是第一个点,移动到该位置
                if (j == 0) {
                    path.moveTo(currentX, currentY);
                } else {// 否则连接上一个点
                    path.lineTo(currentX, currentY);
                }
            }

            path.close();
            canvas.drawPath(path, sidePaint);

        }
    }

    /**
     * 跟具层数判断位于最大半径的位置
     *
     * @param value
     *            第几层
     * @param max
     *            最大层数
     * @return
     */
    private float computeRate(float value, float max) {
        return value / max;
    }

    /*
     * 画出从中心向各顶点的连线
     */
    private void drawLine(Canvas canvas) {
        Path path = new Path();
        for (int i = 0; i < sideCount; i++) {
            path.reset();
            path.lineTo(maxPointList.get(i).getX(), maxPointList.get(i).getY());
            canvas.drawPath(path, sidePaint);
        }
    }

    /**
     * 绘制传入的数值对应的覆盖区域
     *
     * @param canvas
     */
    private void drawArea(Canvas canvas) {
        if (pointValue == null || pointValue.size() == 0)
            return;
        Path path = new Path();
        for (int i = 0; i < pointValue.size(); i++) {
            if (i == 0) {
                areaPaint.setColor(Color.parseColor("#30b4b8"));
            } else if (i == 1) {
                areaPaint.setColor(Color.parseColor("#60b32f"));
            } else if (i == 2) {
                areaPaint.setColor(Color.parseColor("#ef2a34"));
            }
            path.reset();

            // 如果小于三条边 就从中心点开始连线
            if (sideCount < 3) {
                for (int j = 0; j < sideCount; j++) {
                    float rate = pointValue.get(i).get(j);
                    float currentX = maxPointList.get(j).getX() * rate;
                    float currentY = maxPointList.get(j).getY() * rate;
                    path.moveTo(0, 0);
                    path.lineTo(currentX, currentY);
                }
            } else {// 否则连接各个科目成绩点
                for (int j = 0; j < sideCount; j++) {

                    float rate = pointValue.get(i).get(j);
                    float currentX = maxPointList.get(j).getX() * rate;
                    float currentY = maxPointList.get(j).getY() * rate;
                    if (j == 0) {
                        // 如果是第一个点,移动到该位置
                        path.moveTo(currentX, currentY);
                    } else {
                        // 否则连接这个点和上一个点
                        path.lineTo(currentX, currentY);
                    }
                }
            }

            path.close();
            canvas.drawPath(path, areaPaint);
        }

    }

    /**
     * 绘制文字
     *
     * @param canvas
     */
    private void drawText(Canvas canvas) {
        if (pointName == null || pointName.size() == 0) {
            return;
        }
        for (int i = 0; i < pointName.size(); i++) {
            float currentAngle = i * angle;
            if (currentAngle < 180) {
                float currentX = maxPointList.get(i).getX() * 1.1f;
                float currentY = maxPointList.get(i).getY() * 1.1f;
                canvas.drawText(pointName.get(i),
                        currentX - (textPaint.getTextSize() / 4) * (pointName.get(i).length()), currentY, textPaint);
            } else {// 如果大于180度 就让文字靠左
                float currentX = maxPointList.get(i).getX() * 1.2f;
                float currentY = maxPointList.get(i).getY() * 1.2f;
                canvas.drawText(pointName.get(i),
                        currentX - (textPaint.getTextSize() / 4) * (pointName.get(i).length()), currentY, textPaint);
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
    }

    /**
     * 判断是否可以绘制 层数大于0,各边上的数值不能为null
     *
     * @return
     */
    private boolean canDraw() {
        if (loopCount <= 0) {
            return false;
        }
        return true;
    }

    public void setTextColor(int color) {
        textPaint.setColor(color);
    }

    public void setTextSize(int size) {
        textPaint.setTextSize(dpToPixel(size));
    }

    public void setAreaColor(int color) {
        areaPaint.setColor(color);
        areaPaint.setAlpha(150);
    }

    public void setSideColor(int color) {
        sidePaint.setColor(color);
    }

    public void setLoopCount(int loopCount) {
        this.loopCount = loopCount;
    }

    public void setSideCount(int sideCount) {
        if (sideCount <= 0)
            sideCount = 7;
        this.sideCount = sideCount;
        angle = 360 / sideCount;
    }

    public void setPointValue(List<List<Float>> pointValue) {
        this.pointValue = pointValue;
    }

    public void setPointName(List<String> pointName) {
        this.pointName = pointName;
    }

    public int getsideCount() {
        return sideCount;
    }

    public int getLoopCount() {
        return loopCount;
    }

    public List<List<Float>> getPointValue() {
        return pointValue;
    }

    public List<String> getPointName() {
        return pointName;
    }

    public static float dpToPixel(float dp) {
        DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
        return dp * metrics.density;
    }

}
attrs文件
<!-- 多边形 -->
    <declare-styleable name="Polygon">
        <attr name="ptitleColor" format="integer" />
        <attr name="titleSize" format="integer" />
        <attr name="sideCount" format="integer" />
        <attr name="loopCount" format="integer" />
    </declare-styleable>

Point类

public class Point {

    private float x;

    private float y;

    public float getX() {
        return x;
    }

    public void setX(float x) {
        this.x = x;
    }

    public float getY() {
        return y;
    }

    public void setY(float y) {
        this.y = y;
    }

    @Override
    public String toString() {
        return "Point{" +
                "x=" + x +
                ", y=" + y +
                '}';
    }

}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容