前言
前几天有小盆友让我写一个折线图,可以点击,可以左右滑动。对于折线肯定有很多项目都使用过,所以网上肯定也有很多demo,像AndroidChart、HelloChart之类的,功能相当丰富,效果也很赞,但是太重了,其他的小demo又不符合要求,当然了,我写的自定义折线图的思想也有来自这些小demo,对他们表示感谢。
效果图
废话不多说,先上效果图:
效果是不是很赞,如果上图满足你的需求,那就继续往下看。
自定义折线图的步骤:
1、自定义view所需要的属性
确定所需要的自定义view的属性,然后在res/values目录下,新建一个attrs.xml文件,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- xy坐标轴颜色 -->
<attr name="xylinecolor" format="color" />
<!-- xy坐标轴宽度 -->
<attr name="xylinewidth" format="dimension" />
<!-- xy坐标轴文字颜色 -->
<attr name="xytextcolor" format="color" />
<!-- xy坐标轴文字大小 -->
<attr name="xytextsize" format="dimension" />
<!-- 折线图中折线的颜色 -->
<attr name="linecolor" format="color" />
<!-- x轴各个坐标点水平间距 -->
<attr name="interval" format="dimension" />
<!-- 背景颜色 -->
<attr name="bgcolor" format="color" />
<!--是否在ACTION_UP时,根据速度进行自滑动,建议关闭,过于占用GPU-->
<attr name="isScroll" format="boolean" />
<declare-styleable name="chartView">
<attr name="xylinecolor" />
<attr name="xylinewidth" />
<attr name="xytextcolor" />
<attr name="xytextsize" />
<attr name="linecolor" />
<attr name="interval" />
<attr name="bgcolor" />
<attr name="isScroll" />
</declare-styleable>
</resources>
2、在自定义view的构造方法中获取我们的自定义属性:
public ChartView(Context context) {
this(context, null);
}
public ChartView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ChartView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
initPaint();
}
/**
* 初始化
*
* @param context
* @param attrs
* @param defStyleAttr
*/
private void init(Context context, AttributeSet attrs, int defStyleAttr) {
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.chartView, defStyleAttr, 0);
int count = array.getIndexCount();
for (int i = 0; i < count; i++) {
int attr = array.getIndex(i);
switch (attr) {