Android 绘制 环形图

由于项目需要环形图,但是在 MPAndroidChart中没找到 环形图,所以就自己百度搜索总结。

如何你也在搞iOS ,请参考
环形图 - Swift

!无图无真相!效果图如下


效果图

看图,分成左右两个部分,左边 环形图,右边是说明 百分比值等等,
我只绘制了左边,右边用View堆起来就好!

一 、分析需要哪些 数据

确定 中间的空白圆的半径 r
确定 环形的宽度 ringWidth
确定 环形之间的间距 ringSpace
确定 环形 个数 ringCount
其他颜色等

二、绘制及其计算

1、绘制 最里面的环形

绘制的中心点:即view的中心;
绘制的半径:空白圆的半径 r + 环形宽度 / 2
可以理解为:先用圆规画了一个圆线,然后用彩笔笔尖对准圆线进行涂写,就画出来了一个圆环。。。

2、绘制 中间的环形

绘制的中心点:即view的中心;
绘制的半径:空白圆的半径 r + 环形宽度 + 环形间距 + 环形宽度 / 2

3、绘制 最外层的环形

绘制的中心点:即view的中心;
绘制的半径:空白圆的半径 r + 环形宽度2 + 环形间距2 + 环形宽度 / 2

4、绘制中间的文本

绘制的中心点:即view的中心;
绘制文本的最大宽度:空白圆的半径 r
如何换行?

完整代码如下:

一共就 6 个文件, 只要copy到自己工程中去,修改 import 包就可以了

  • colors.xml
  • attrs.xml
  • 环形类 LzRingChart.java
  • common_circle.xml
  • activity_main.xml
  • MainActivity.java

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimaryDark">#00000000</color>
    <color name="colorAccent">#D81B60</color>

    <color name="main">#33a3dc</color>

    <color name="black1">#111111</color>
    <color name="black2">#333333</color>
    <color name="black3">#666666</color>
    <color name="black4">#999999</color>
    <color name="over_layer">#99000000</color>

    <color name="white">#ffffff</color>

    <color name="line_cf">#cfcfcf</color>
    <color name="line_d8">#d8d8d8</color>
    <color name="line_e5">#e5e5e5</color>
    <color name="line_f5">#f5f5f5</color>

    <color name="c1">#b64533</color>
    <color name="c2">#c85d44</color>
    <color name="c3">#f15a22</color>
    <color name="c4">#cbc547</color>
    <color name="c5">#fdb933</color>
    <color name="c6">#e0861a</color>
    <color name="c7">#bed742</color>
    <color name="c8">#7fb80e</color>
    <color name="c9">#77ac98</color>
    <color name="c10">#50b7c1</color>
    <color name="c11">#c77eb5</color>
    <color name="c12">#6f60aa</color>

</resources>

attr.xml 文件

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="LzRingChart">
        <attr name="innerRadius" format="dimension"/>
        <attr name="ringWidth" format="dimension"/>
        <attr name="ringSpace" format="dimension" />
        <attr name="ringBgColor" format="color"/>
        <attr name="ringCount" format="integer"/>
    </declare-styleable>

</resources>

common_circle.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >
    <solid android:color="#999999"/>
    <size android:width="6dp"
        android:height="6dp"/>
</shape>

环形图 LzRingChart.java

package com.lz.ui;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.lz.tool.DeviceTool;
import com.lz.wehome.R;

public class LzRingChart extends View {
    //中间的半径, 环形的宽度,环形间距, 环形背景颜色,环形的数量
    int innerRadius, ringWidth, ringSpace, ringBgColor, ringCount;
    //环形画笔
    Paint ringBgPaint;
    //文本画笔
    TextPaint textPaint;

    Rect textRect;
    RectF ringRectF;

    //百分比 0.xxx
    float[] values;
    //环形百分比颜色
    int[] colors;
    CharSequence title;
    private Context context;

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

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

    public LzRingChart(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;

        //读取xml中值
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.LzRingChart, defStyleAttr, 0);
        innerRadius = typedArray.getDimensionPixelSize(R.styleable.LzRingChart_innerRadius, DeviceTool.dp2px(context, 50));
        ringWidth = typedArray.getDimensionPixelSize(R.styleable.LzRingChart_ringWidth, DeviceTool.dp2px(context, 5));
        ringSpace = typedArray.getDimensionPixelSize(R.styleable.LzRingChart_ringSpace, DeviceTool.dp2px(context, 5));
        ringBgColor = typedArray.getColor(R.styleable.LzRingChart_ringBgColor, ContextCompat.getColor(context, R.color.line_d8));
        ringCount = typedArray.getInt(R.styleable.LzRingChart_ringCount, 1);

        typedArray.recycle();
        initPaint();
    }


    /**
     * 配置
     */
    void initPaint() {
        //绘制圆环
        ringBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        ringBgPaint.setStyle(Paint.Style.STROKE);
        ringBgPaint.setColor(ringBgColor);
        ringBgPaint.setStrokeWidth(ringWidth);

        textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        textPaint.setColor(context.getResources().getColor(R.color.main));
        textPaint.setTextSize(DeviceTool.dp2px(context, 13));

        textRect = new Rect();
        ringRectF = new RectF();

//        invalidate();
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //测量尺寸
        setMeasuredDimension(measureView(widthMeasureSpec), measureView(heightMeasureSpec));

    }

    /**
     * 测量尺寸
     */
    private int measureView(int measureSpec) {
        int result;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        if(specMode == MeasureSpec.EXACTLY){
            result = specSize;

            /**
             * 比较 xml设置的 View宽高 是否小于半径等
             */
            int real = (innerRadius + ringSpace*(ringCount-1) + ringWidth*ringCount)*2;
            if (real > specSize) {
                result = real;
            }
        }else{
            result = (innerRadius + ringSpace*(ringCount-1) + ringWidth*ringCount)*2;
            if(specMode==MeasureSpec.AT_MOST){
                result=Math.min(result,specSize);
            }
        }
        return result;
    }


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

        //绘制背景色圆环
        drawBgRing(canvas);

        //百分比圆环
        drawPercentRing(canvas);

        //中间文本
        drawCenterText(canvas);
    }

    /**
     * 绘制 环形中间的文本
     */
    void drawCenterText(Canvas canvas) {
        if (title==null) return;
        StaticLayout sl = new StaticLayout(title, textPaint, innerRadius*2, Layout.Alignment.ALIGN_CENTER, 1.1f, 0, true);
        canvas.translate(getWidth()/2-sl.getWidth()/2, getHeight()/2-sl.getHeight()/2);
        sl.draw(canvas);
    }


    /**
     * 绘制 默认颜色的环形
     */
    void drawBgRing(Canvas canvas) {
        //需要重新设置一下
        ringBgPaint.setColor(ringBgColor);

        for (int i = 0; i < ringCount; i++) {
            float letf = getWidth()/2 - innerRadius - ringWidth*(ringCount-i) - (ringCount-1-i)*ringSpace + ringWidth/2;
            float top = getHeight()/2 - innerRadius - ringWidth*(ringCount-i) - (ringCount-1-i)*ringSpace + ringWidth/2;
            float right = getWidth()/2 + innerRadius + ringWidth*(ringCount-i) + (ringCount-1-i)*ringSpace - ringWidth/2;
            float bottom = getHeight()/2 + innerRadius + ringWidth*(ringCount-i) + (ringCount-1-i)*ringSpace - ringWidth/2;
            ringRectF.set(letf, top, right, bottom);
            canvas.drawArc(ringRectF, 0, 360,false, ringBgPaint);
        }
    }


    /**
     * 绘制百分比的环形
     */
    void drawPercentRing(Canvas canvas) {

        if (values == null || values.length ==0) return;
        for (int i = 0; i < values.length; i++) {
            ringBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            ringBgPaint.setStyle(Paint.Style.STROKE);
            ringBgPaint.setColor(context.getResources().getColor(colors[i]));
            ringBgPaint.setStrokeWidth(ringWidth);
            float letf = getWidth()/2 - innerRadius - ringWidth*(ringCount-i) - (ringCount-1-i)*ringSpace + ringWidth/2;
            float top = getHeight()/2 - innerRadius - ringWidth*(ringCount-i) - (ringCount-1-i)*ringSpace + ringWidth/2;
            float right = getWidth()/2 + innerRadius + ringWidth*(ringCount-i) + (ringCount-1-i)*ringSpace - ringWidth/2;
            float bottom = getHeight()/2 + innerRadius + ringWidth*(ringCount-i) + (ringCount-1-i)*ringSpace - ringWidth/2;
            ringRectF.set(letf, top, right, bottom);
            float sweepAngle = 360*values[i];
            if (sweepAngle >= 360) sweepAngle = 360;
            canvas.drawArc(ringRectF, -90, sweepAngle,false, ringBgPaint);
        }
    }


    /**
     * 设置 数据
     * @param title 中间的标题
     * @param values 百分比的值
     * @param colors 颜色值
     */
    public void setData(CharSequence title, float[] values, int[] colors) {
        this.title = title;
        this.values = values;
        this.colors = colors;
        invalidate();
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    >

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardCornerRadius="10dp"
        android:layout_margin="10dp"
        >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:gravity="center"
            android:background="#f5f5f5"
            android:padding="10dp"
            >

            <com.lz.ui.LzRingChart
                android:id="@+id/chart_ring"
                android:layout_width="100dp"
                android:layout_height="100dp"
                app:ringCount="3"
                app:ringSpace="5dp"
                app:ringWidth="5dp"
                app:innerRadius="60dp"
                app:ringBgColor="#eee"
                />

            <LinearLayout
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:paddingStart="10dp"
                android:paddingEnd="10dp"
                >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:gravity="center_vertical"
                    >
                    <View
                        android:id="@+id/view_mark1"
                        android:layout_width="6dp"
                        android:layout_height="6dp"
                        android:background="@drawable/common_circle"
                        />

                    <TextView
                        android:id="@+id/tv_t1"
                        android:layout_width="wrap_content"
                        android:layout_height="30dp"
                        android:gravity="center_vertical"
                        android:textColor="@color/c1"
                        android:text="深度"
                        android:textSize="18sp"
                        android:layout_marginStart="10dp"
                        />
                </LinearLayout>
                <TextView
                    android:id="@+id/tv_value1"
                    android:layout_width="wrap_content"
                    android:layout_height="30dp"
                    android:gravity="center_vertical"
                    android:textColor="@color/black3"
                    android:text="其他描述信息"
                    android:textSize="13sp"
                    android:layout_marginStart="10dp"
                    />


                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:gravity="center_vertical"
                    >
                    <View
                        android:id="@+id/view_mark2"
                        android:layout_width="6dp"
                        android:layout_height="6dp"
                        android:background="@drawable/common_circle"
                        />

                    <TextView
                        android:id="@+id/tv_t2"
                        android:layout_width="wrap_content"
                        android:layout_height="30dp"
                        android:gravity="center_vertical"
                        android:textColor="@color/c8"
                        android:text="深度"
                        android:textSize="18sp"
                        android:layout_marginStart="10dp"
                        />
                </LinearLayout>
                <TextView
                    android:id="@+id/tv_value2"
                    android:layout_width="wrap_content"
                    android:layout_height="30dp"
                    android:gravity="center_vertical"
                    android:textColor="@color/black3"
                    android:text="其他描述信息"
                    android:textSize="13sp"
                    android:layout_marginStart="10dp"
                    />


                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:gravity="center_vertical"
                    >
                    <View
                        android:id="@+id/view_mark3"
                        android:layout_width="6dp"
                        android:layout_height="6dp"
                        android:background="@drawable/common_circle"
                        />

                    <TextView
                        android:id="@+id/tv_t3"
                        android:layout_width="wrap_content"
                        android:layout_height="30dp"
                        android:gravity="center_vertical"
                        android:textColor="@color/c12"
                        android:text="清醒"
                        android:textSize="18sp"
                        android:layout_marginStart="10dp"
                        />
                </LinearLayout>
                <TextView
                    android:id="@+id/tv_value3"
                    android:layout_width="wrap_content"
                    android:layout_height="30dp"
                    android:gravity="center_vertical"
                    android:textColor="@color/black3"
                    android:text="其他描述信息"
                    android:textSize="13sp"
                    android:layout_marginStart="10dp"
                    />

            </LinearLayout>

        </LinearLayout>

    </androidx.cardview.widget.CardView>

</LinearLayout>

MainActivity.java

主要代码


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        showRingChart();

    }

    private LzRingChart ringChart;
    private View vMark1, vMark2, vMark3;
    void showRingChart() {
        ringChart = findViewById(R.id.chart_ring);

        String totalStr = "08:00";
        SpannableString s = new SpannableString(totalStr + "\n睡眠总时长");
        s.setSpan(new RelativeSizeSpan(2.7f), 0, totalStr.length(), 0);
        s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.black3)), totalStr.length(), s.length(), 0);
        s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.main)), 0, totalStr.length(), 0);

        ringChart.setData(s, new float[]{0.5f, 0.5f, 0}, new int[]{R.color.c1, R.color.c8, R.color.c12});

        vMark1 = findViewById(R.id.view_mark1);
        vMark2 = findViewById(R.id.view_mark2);
        vMark3 = findViewById(R.id.view_mark3);

        GradientDrawable gd1 = (GradientDrawable) vMark1.getBackground();
        gd1.setColor(getResources().getColor(R.color.c1));

        GradientDrawable gd2 = (GradientDrawable) vMark2.getBackground();
        gd2.setColor(getResources().getColor(R.color.c8));

        GradientDrawable gd3 = (GradientDrawable) vMark3.getBackground();
        gd3.setColor(getResources().getColor(R.color.c12));

    }

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