详解Android自定义View--自定义柱状图
绪论
转眼间,2016伴随着互联网寒冬和帝都的雾霾马上就过去了,不知道大家今年一整年过得怎么样?最近票圈被各个城市的雾霾刷屏,内心难免会动荡,庆幸自己早出来一年,也担忧着自己的未来的职业规划。无所谓了,既然选择了这个行业,我觉得大家就应该坚持下去,路是自己走的,及时再寒冬,只要你足够优秀,足够努力,相信你最后还是会找到自己满意的工作的。最后还要感谢今年博客之星大家对我的投票支持,非常感谢。不多说了,今天的主题是它–对,自定义view柱状图。
先来说说我最近在做什么吧?好久没有写博客了,最近手里有两个项目,闲的时候一直在忙着做项目,也封装了属于自己的一套library,抽下来我会把它分享出来的。公司的项目也一直在忙,今天的柱状图就是公司的项目所用到的。先来看一下效果吧
具体实现
可以看到,今天的柱状图分为三类:双条竖向柱状图、单条竖向柱状图以及单条横向柱状图,其实原理都是一样的,下面我们具体看一下怎么实现,怎么去画一个这样的柱状图。
双条竖向
我们可以看到这个柱状图主要包括下面几个方面:
- 双条柱状图
- 横坐标月份
- 点击tips显示具体数值
- 灰色阴影(图上没有显示具体看代码)
- 柱状图渐变、圆角、点击变色
好了上面五点就是需求和ui所提出来的所有东西,我们开始着手去“画”吧。
1.首先我们定义一些资源style供使用
包括
- leftcolor 左侧柱状图顶部颜色
- leftcolorbottom 左侧柱状图底部颜色
- rightcolor 右侧柱状图顶部颜色
- rightcolorbottom 右侧柱状图底部颜色
- selectrightcolor 左侧点击选中颜色
- selectrightcolor 右侧点击选中颜色
- xycolor 横轴字体颜色
底部和顶部颜色是用于渐变用的
<declare-styleable name="mychartview"> <attr name="leftcolor" format="color"></attr> <attr name="leftcolorbottom" format="color"></attr> <attr name="selectleftcolor" format="color"></attr> <attr name="rightcolor" format="color"></attr> <attr name="rightcolorbottom" format="color"></attr> <attr name="selectrightcolor" format="color"></attr> <attr name="xycolor" format="color"></attr> </declare-styleable>
2.接下来我们看具体代码,注释写的很详细了,仔细看:
- 初始化属性、画笔、所用的size等
- 测量计算高宽度等
- 画坐标轴、画月份、画柱状图、画阴影
- 柱状图渐变以及点击变色
- touch点击事件判断点击所属哪个月份,接口回调给activity显示具体月份数值
注意:onwindowvisibilitychanged这个方法(当屏幕焦点变化时重新侧向起始位置,必须重写次方法,否则当焦点变化时柱状图会跑到屏幕外面)
下面主要说一下绘制部分吧
ondraw()部分
我们将每次ontouch的条的索引放到selectindexroles数组中,然后当这个数组包含该绘制的柱状图的索引是我们设置不用颜色以及不设置渐变;
同时我们给每两个双条之间的的空白处绘制成阴影;
最后drawroundrect()就绘制了一个圆角的矩形。
//画柱状图 for (int i = 0; i < list.size(); i++) { int size = mheight / 120; if (selectindexroles.contains(i)) { //偶数 mchartpaint.setshader(null); if (i % 2 == 0) { mchartpaint.setcolor(selectleftcolor); } else { mchartpaint.setcolor(selectrightcolor); } } else { //偶数 if (i % 2 == 0) { lineargradient lg = new lineargradient(mchartwidth, mchartwidth + msize, mheight - 100, (float) (mheight - 100 - list.get(i) * size), lefrcolorbottom, leftcolor, shader.tilemode.mirror); mchartpaint.setshader(lg); } else { lineargradient lg = new lineargradient(mchartwidth, mchartwidth + msize, mheight - 100, (float) (mheight - 100 - list.get(i) * size), rightcolorbottom, rightcolor, shader.tilemode.mirror); mchartpaint.setshader(lg); } } mchartpaint.setstyle(paint.style.fill); //画阴影 if (i == number * 2 || i == number * 2 + 1) { mshadowpaint.setcolor(color.blue); } else { mshadowpaint.setcolor(color.white); } //画柱状图 rectf rectf = new rectf(); rectf.left = mchartwidth; rectf.right = mchartwidth + msize; rectf.bottom = mheight - 100; rectf.top = (float) (mheight - 100 - list.get(i) * size); canvas.drawroundrect(rectf, 10, 10, mchartpaint); //canvas.drawrect(mchartwidth, mheight - 100 - list.get(i) * size, mchartwidth + msize, mheight - 100, mchartpaint) // ;// 长方形 mchartwidth += (i % 2 == 0) ? (3 + getwidth() / 39) : (getwidth() / 13 - 3 - msize); }
全部代码
package com.hankkin.mycartdemo.chatview; import android.content.context; import android.content.res.typedarray; import android.graphics.canvas; import android.graphics.color; import android.graphics.lineargradient; import android.graphics.paint; import android.graphics.rect; import android.graphics.rectf; import android.graphics.shader; import android.util.attributeset; import android.view.motionevent; import android.view.view; import com.hankkin.mycartdemo.r; import java.util.arraylist; import java.util.list; /** * created by hankkin on 2016/12/10. */ public class mychartview extends view { private int leftcolor;//双柱左侧 private int rightcolor;//双柱右侧 private int linecolor;//横轴线 private int selectleftcolor;//点击选中左侧 private int selectrightcolor;//点击选中右侧 private int lefrcolorbottom;//左侧底部 private int rightcolorbottom;//右侧底部 private paint mpaint, mchartpaint, mshadowpaint;//横轴画笔、柱状图画笔、阴影画笔 private int mwidth, mheight, mstartwidth, mchartwidth, msize;//屏幕宽度高度、柱状图起始位置、柱状图宽度 private rect mbound; private list<float> list = new arraylist<>();//柱状图高度占比 private rect rect;//柱状图矩形 private getnumberlistener listener;//点击接口 private int number = 1000;//柱状图最大值 private int selectindex = -1;//点击选中柱状图索引 private list<integer> selectindexroles = new arraylist<>(); public void setlist(list<float> list) { this.list = list; msize = getwidth() / 39; mstartwidth = getwidth() / 13; mchartwidth = getwidth() / 13 - msize - 3; invalidate(); } public void setlistener(getnumberlistener listener) { this.listener = listener; } public mychartview(context context) { this(context, null); } public mychartview(context context, attributeset attrs) { this(context, attrs, 0); } public mychartview(context context, attributeset attrs, int defstyleattr) { super(context, attrs, defstyleattr); //获取我们自定义的样式属性 typedarray array = context.gettheme().obtainstyledattributes(attrs, r.styleable.mychartview, defstyleattr, 0); int n = array.getindexcount(); for (int i = 0; i < n; i++) { int attr = array.getindex(i); switch (attr) { case r.styleable.mychartview_leftcolor: // 默认颜色设置为黑色 leftcolor = array.getcolor(attr, color.black); break; case r.styleable.mychartview_selectleftcolor: // 默认颜色设置为黑色 selectleftcolor = array.getcolor(attr, color.black); break; case r.styleable.mychartview_rightcolor: rightcolor = array.getcolor(attr, color.black); break; case r.styleable.mychartview_selectrightcolor: selectrightcolor = array.getcolor(attr, color.black); break; case r.styleable.mychartview_xycolor: linecolor = array.getcolor(attr, color.black); break; case r.styleable.mychartview_leftcolorbottom: lefrcolorbottom = array.getcolor(attr, color.black); break; case r.styleable.mychartview_rightcolorbottom: rightcolorbottom = array.getcolor(attr, color.black); break; } } array.recycle(); init(); } //初始化画笔 private void init() { mpaint = new paint(); mpaint.setantialias(true); mbound = new rect(); mchartpaint = new paint(); mchartpaint.setantialias(true); mshadowpaint = new paint(); mshadowpaint.setantialias(true); mshadowpaint.setcolor(color.white); } //测量高宽度 @override protected void onmeasure(int widthmeasurespec, int heightmeasurespec) { super.onmeasure(widthmeasurespec, heightmeasurespec); int width; int height; int widthsize = measurespec.getsize(widthmeasurespec); int heightsize = measurespec.getsize(heightmeasurespec); int widthmode = measurespec.getmode(widthmeasurespec); int heightmode = measurespec.getmode(heightmeasurespec); if (widthmode == measurespec.exactly) { width = widthsize; } else { width = widthsize * 1 / 2; } if (heightmode == measurespec.exactly) { height = heightsize; } else { height = heightsize * 1 / 2; } setmeasureddimension(width, height); } //计算高度宽度 @override protected void onlayout(boolean changed, int left, int top, int right, int bottom) { super.onlayout(changed, left, top, right, bottom); mwidth = getwidth(); mheight = getheight(); mstartwidth = getwidth() / 13; msize = getwidth() / 39; mchartwidth = getwidth() / 13 - msize; } //重写ondraw绘制 @override protected void ondraw(canvas canvas) { super.ondraw(canvas); mpaint.setcolor(linecolor); //画坐标轴 //canvas.drawline(0, mheight - 100, mwidth, mheight - 100, mpaint); for (int i = 0; i < 12; i++) { //画刻度线 //canvas.drawline(mstartwidth, mheight - 100, mstartwidth, mheight - 80, mpaint); //画数字 mpaint.settextsize(35); mpaint.settextalign(paint.align.center); mpaint.gettextbounds(string.valueof(i + 1) + "", 0, string.valueof(i).length(), mbound); canvas.drawtext(string.valueof(i + 1) + "月", mstartwidth - mbound.width() * 1 / 2, mheight - 60 + mbound.height() * 1 / 2, mpaint); mstartwidth += getwidth() / 13; } //画柱状图 for (int i = 0; i < list.size(); i++) { int size = mheight / 120; if (selectindexroles.contains(i)) { //偶数 mchartpaint.setshader(null); if (i % 2 == 0) { mchartpaint.setcolor(selectleftcolor); } else { mchartpaint.setcolor(selectrightcolor); } } else { //偶数 if (i % 2 == 0) { lineargradient lg = new lineargradient(mchartwidth, mchartwidth + msize, mheight - 100, (float) (mheight - 100 - list.get(i) * size), lefrcolorbottom, leftcolor, shader.tilemode.mirror); mchartpaint.setshader(lg); } else { lineargradient lg = new lineargradient(mchartwidth, mchartwidth + msize, mheight - 100, (float) (mheight - 100 - list.get(i) * size), rightcolorbottom, rightcolor, shader.tilemode.mirror); mchartpaint.setshader(lg); } } mchartpaint.setstyle(paint.style.fill); //画阴影 if (i == number * 2 || i == number * 2 + 1) { mshadowpaint.setcolor(color.blue); } else { mshadowpaint.setcolor(color.white); } //画柱状图 rectf rectf = new rectf(); rectf.left = mchartwidth; rectf.right = mchartwidth + msize; rectf.bottom = mheight - 100; rectf.top = (float) (mheight - 100 - list.get(i) * size); canvas.drawroundrect(rectf, 10, 10, mchartpaint); //canvas.drawrect(mchartwidth, mheight - 100 - list.get(i) * size, mchartwidth + msize, mheight - 100, mchartpaint) // ;// 长方形 mchartwidth += (i % 2 == 0) ? (3 + getwidth() / 39) : (getwidth() / 13 - 3 - msize); } } @override public void onwindowfocuschanged(boolean haswindowfocus) { super.onwindowfocuschanged(haswindowfocus); if (haswindowfocus) { } } /** * 注意: * 当屏幕焦点变化时重新侧向起始位置,必须重写次方法,否则当焦点变化时柱状图会跑到屏幕外面 */ @override protected void onwindowvisibilitychanged(int visibility) { super.onwindowvisibilitychanged(visibility); if (visibility == visible) { msize = getwidth() / 39; mstartwidth = getwidth() / 13; mchartwidth = getwidth() / 13 - msize - 3; } } /** * 柱状图touch事件 * 获取触摸位置计算属于哪个月份的 * @param ev * @return */ @override public boolean ontouchevent(motionevent ev) { int x = (int) ev.getx(); int y = (int) ev.gety(); int left = 0; int top = 0; int right = mwidth / 12; int bottom = mheight - 100; switch (ev.getaction()) { case motionevent.action_down: for (int i = 0; i < 12; i++) { rect = new rect(left, top, right, bottom); left += mwidth / 12; right += mwidth / 12; if (rect.contains(x, y)) { listener.getnumber(i, x, y); number = i; selectindex = i; selectindexroles.clear(); ; selectindexroles.add(selectindex * 2 + 1); selectindexroles.add(selectindex * 2); invalidate(); } } break; case motionevent.action_up: break; } return true; } public interface getnumberlistener { void getnumber(int number, int x, int y); } public int getleftcolor() { return leftcolor; } public void setleftcolor(int leftcolor) { this.leftcolor = leftcolor; } public int getrightcolor() { return rightcolor; } public void setrightcolor(int rightcolor) { this.rightcolor = rightcolor; } public int getlinecolor() { return linecolor; } public void setlinecolor(int linecolor) { this.linecolor = linecolor; } public int getselectleftcolor() { return selectleftcolor; } public void setselectleftcolor(int selectleftcolor) { this.selectleftcolor = selectleftcolor; } public int getselectrightcolor() { return selectrightcolor; } public void setselectrightcolor(int selectrightcolor) { this.selectrightcolor = selectrightcolor; } public int getlefrcolorbottom() { return lefrcolorbottom; } public void setlefrcolorbottom(int lefrcolorbottom) { this.lefrcolorbottom = lefrcolorbottom; } public int getrightcolorbottom() { return rightcolorbottom; } public void setrightcolorbottom(int rightcolorbottom) { this.rightcolorbottom = rightcolorbottom; } }
3.具体使用:
private void initchatview() { mychartview.setlefrcolorbottom(getresources().getcolor(r.color.leftcolorbottom)); mychartview.setleftcolor(getresources().getcolor(r.color.leftcolor)); mychartview.setrightcolor(getresources().getcolor(r.color.rightcolor)); mychartview.setrightcolorbottom(getresources().getcolor(r.color.rightbottomcolor)); mychartview.setselectleftcolor(getresources().getcolor(r.color.selectleftcolor)); mychartview.setselectrightcolor(getresources().getcolor(r.color.selectrightcolor)); mychartview.setlinecolor(getresources().getcolor(r.color.xycolor)); chartlist = new arraylist<>(); relativelayout = (relativelayout) findviewbyid(r.id.linearlayout); relativelayout.removeview(llchart); random random = new random(); while (chartlist.size() < 24) { int randomint = random.nextint(100); chartlist.add((float) randomint); } mychartview.setlist(chartlist); mychartview.setlistener(new mychartview.getnumberlistener() { @override public void getnumber(int number, int x, int y) { relativelayout.removeview(llchart); //反射加载点击柱状图弹出布局 llchart = (linearlayout) layoutinflater.from(mainactivity.this).inflate(r.layout.layout_shouru_zhichu, null); textview tvzhichu = (textview) llchart.findviewbyid(r.id.tv_zhichu); textview tvshouru = (textview) llchart.findviewbyid(r.id.tv_shouru); tvzhichu.settext((number + 1) + "月支出" + " " + chartlist.get(number * 2)); tvshouru.settext ( "收入: " + chartlist.get(number * 2 + 1)); llchart.measure(0, 0);//调用该方法后才能获取到布局的宽度 relativelayout.layoutparams params = new relativelayout.layoutparams(relativelayout.layoutparams.wrap_content, relativelayout.layoutparams.wrap_content); params.leftmargin = x - 100; if (x - 100 < 0) { params.leftmargin = 0; } else if (x - 100 > relativelayout.getwidth() - llchart.getmeasuredwidth()) { //设置布局距左侧屏幕宽度减去布局宽度 params.leftmargin = relativelayout.getwidth() - llchart.getmeasuredwidth(); } llchart.setlayoutparams(params); relativelayout.addview(llchart); } }); }
经过以上步骤,我们的双条竖向柱状图就绘制完成了,也显示出来了。其实自己坐下来仔细拿笔算一下,画一下,也没有想象的那么难。至于单条和横向的实现原理都一样,比这个要简单的多。哦对了,横向的我只是自定义了一个横向的柱状图view,然后用listview显示的各个部门的具体内容。
代码下载:demo
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
推荐阅读