Android自定义View之直方图和扇形图——ChartView

本文介绍了如何在Android中自定义一个名为ChartView的视图,该视图能够同时显示柱状图和扇形图。通过自定义属性如chartType、proportion、axisColor和sectionAmount来控制图表样式。在`onMeasure`方法中处理视图高度,并实现了柱状图和扇形图的绘制。此外,还添加了动画效果,利用ValueAnimator动态改变柱状图的高度或扇形图的角度。最后,提供了源码链接供读者参考。
摘要由CSDN通过智能技术生成

先上图

这里写图片描述

实现

      因为本次需求中只有柱状图和扇形图的需求,所以本次示例将两种类型的图放在了一个view里,先看看自定义属性

<declare-styleable name="ChartView">
        <attr name="textColor" format="color" />
        <attr name="textSize" format="dimension" />
        <attr name="chartType" format="enum">
            <enum name="HISTOGRAM" value="101"/>
            <enum name="FAN" value="102"/>
        </attr>
        <attr name="proportion" format="integer"/>
        <attr name="axisColor" format="color"/>
        <attr name="sectionColor" format="color"/>
        <attr name="sectionAmount" format="integer"/>
    </declare-styleable>

      其中chartType表示图表类型,也就是上面提到的柱状或扇形图,proportion表示在柱状图里,每个柱子与柱子之间的间隔的宽度比,axisColor为坐标轴的颜色,sectionAmount表示坐标轴分成几个区间并且以横线将坐标轴分成对应个区域。

onMeasure

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);

        //默认以w/h : 16/12 的形式展现
        int screenWidth = getResources().getDisplayMet
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值