概述
折线图在很多的项目中都会出现,作为数据直观的展示。在之前的一个房地产数据管理的项目中,用到了很多统计图,起初也在网上看过一些图表库,但是大部分都不能满足UI给出的样式,所有只能自己搞了,把项目中的代码抽离了一些出来,下面手写了一个折线图。
效果图!
动图
实现
功能
- 支持多种折线数据共同显示
- 每种折线和点的颜色可配置
- 折线图可使用从左到右展开动画
- 支持设置圆滑的曲线
- 显示隐藏折线上数据值
- 显示隐藏折线上数据点
自定义属性
根据自己的需要,定义一些属性,其他使用默认的也行。
<declare-styleable name="TotcyChart">
<attr name="TextSize" format="dimension"/>
<attr name="YscaleHeight" format="dimension" />
<attr name="ChartPandding" format="dimension" />
<attr name="ChartLineWidth" format="dimension" />
</declare-styleable>
获取自定义属性
构造方法中获取。
/**
* 获得所有自定义的参数的值
*/
TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
R.styleable.TotcyChart, defStyleAttr, 0);
int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = a.getIndex(i);
if (attr == R.styleable.TotcyChart_TextSize) {
axisSize = (int) a.getDimension(attr, axisSize);
} else if (attr == R.styleable.TotcyChart_YscaleHeight) {
yScaleHeight = (int) a.getDimension(attr, yScaleHeight);
} else if (attr == R.styleable.TotcyChart_ChartPandding) {
padding = a.getDimension(attr, padding);
} else if (attr == R.styleable.TotcyChart_ChartLineWidth) {
lineStrokeWidth = a.getDimension(attr, lineStrokeWidth);
} else {
}
}
a.recycle();
初始化
绘制折线图,或者是其他的统计图,都可以从以下几点入手:
1、原点坐标(x,y);
yCount是y坐标数据的个数
圆点Y轴坐标 上面padding +xTabHeight +(yCount-1个y轴间隔)
dotY = padding + xTabHeight + (yCount - 1) * yScaleHeight;
圆点X轴坐标 左边距padding +画笔绘制最大值的长度