先上图
实现
因为本次需求中只有柱状图和扇形图的需求,所以本次示例将两种类型的图放在了一个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