Android实现炫酷的CheckBox效果
首先贴出实现的效果图:
gif的效果可能有点过快,在真机上运行的效果会更好一些。我们主要的思路就是利用属性动画来动态地画出选中状态以及对勾的绘制过程。看到上面的效果图,相信大家都迫不及待地要跃跃欲试了,那就让我们开始吧。
自定义view的第一步:自定义属性。
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="smoothcheckbox"> <!-- 动画持续时间 --> <attr name="duration" format="integer"></attr> <!-- 边框宽度 --> <attr name="strikewidth" format="dimension|reference"></attr> <!-- 边框颜色 --> <attr name="bordercolor" format="color|reference"></attr> <!-- 选中状态的颜色 --> <attr name="trimcolor" format="color|reference"></attr> <!-- 对勾颜色 --> <attr name="tickcolor" format="color|reference"></attr> <!-- 对勾宽度 --> <attr name="tickwidth" format="dimension|reference"></attr> </declare-styleable> </resources>
我们把checkbox取名为smoothcheckbox,定义了几个等等要用到的属性。这一步很简单,相信大家都熟练了。
接下来看一看onmeasure(int widthmeasurespec, int heightmeasurespec):
@override protected void onmeasure(int widthmeasurespec, int heightmeasurespec) { super.onmeasure(widthmeasurespec, heightmeasurespec); int widthsize = measurespec.getsize(widthmeasurespec); int widthmode = measurespec.getmode(widthmeasurespec); if (widthmode == measurespec.exactly) { mwidth = widthsize; } else { mwidth = 40; } int heightsize = measurespec.getsize(heightmeasurespec); int heightmode = measurespec.getmode(heightmeasurespec); if (heightmode == measurespec.exactly) { mheight = heightsize; } else { mheight = 40; } setmeasureddimension(mwidth, mheight); int size = math.min(mwidth, mheight); center = size / 2; mradius = (int) ((size - mstrokewidth) / 2 / 1.2f); startpoint.set(center * 14 / 30, center * 28 / 30); breakpoint.set(center * 26 / 30, center * 40 / 30); endpoint.set(center * 44 / 30, center * 20 / 30); downlength = (float) math.sqrt(math.pow(startpoint.x - breakpoint.x, 2f) + math.pow(startpoint.y - breakpoint.y, 2f)); uplength = (float) math.sqrt(math.pow(endpoint.x - breakpoint.x, 2f) + math.pow(endpoint.y - breakpoint.y, 2f)); totallength = downlength + uplength; }
一开始是测量了smoothcheckbox的宽、高度,默认的宽高度随便定义了一个,当然你们可以自己去修改和完善它。然后就是设置半径之类的,最后的startpoint、breakpoint、endpoint分别对应着选中时对勾的三个点(至于为何是这几个数字,那完全是经验值);downlength就是startpoint和breakpoint的距离,而相对应的uplength就是breakpoint和endpoint的距离。即以下图示:
在看ondraw(canvas canvas)之前我们先来看两组动画,分别是选中状态时的动画以及未选中状态的动画:
// 由未选中到选中的动画 private void checkedanimation() { animatedvalue = 0f; tickvalue = 0f; // 选中时底色的动画 mvalueanimator = valueanimator.offloat(0f, 1.2f, 1f).setduration(2 * duration / 5); mvalueanimator.setinterpolator(new acceleratedecelerateinterpolator()); // 对勾的动画 mtickvalueanimator = valueanimator.offloat(0f, 1f).setduration(3 * duration / 5); mtickvalueanimator.setinterpolator(new linearinterpolator()); mtickvalueanimator.addupdatelistener(new valueanimator.animatorupdatelistener() { @override public void onanimationupdate(valueanimator valueanimator) { // 得到动画执行进度 tickvalue = (float) valueanimator.getanimatedvalue(); postinvalidate(); } }); mvalueanimator.addupdatelistener(new valueanimator.animatorupdatelistener() { @override public void onanimationupdate(valueanimator valueanimator) { // 得到动画执行进度 animatedvalue = (float) valueanimator.getanimatedvalue(); postinvalidate(); } }); mvalueanimator.addlistener(new animatorlisteneradapter() { @override public void onanimationend(animator animation) { //当底色的动画完成后再开始对勾的动画 mtickvalueanimator.start(); log.i(tag," mtickvalueanimator.start();"); } }); mvalueanimator.start(); } // 由选中到未选中的动画 private void uncheckedanimation() { animatedvalue = 0f; mvalueanimator = valueanimator.offloat(1f, 0f).setduration(2 * duration / 5); mvalueanimator.setinterpolator(new accelerateinterpolator()); mvalueanimator.addupdatelistener(new valueanimator.animatorupdatelistener() { @override public void onanimationupdate(valueanimator valueanimator) { animatedvalue = (float) valueanimator.getanimatedvalue(); postinvalidate(); } }); mvalueanimator.start(); }
这两组动画在点击smoothcheckbox的时候会调用。相似的,都是在动画执行中得到动画执行的进度,再来调用postinvalidate();让smoothcheckbox重绘。看完这个之后就是终极大招ondraw(canvas canvas)了:
@override protected void ondraw(canvas canvas) { super.ondraw(canvas); canvas.save(); drawborder(canvas); drawtrim(canvas); if (ischecked) { drawtick(canvas); } canvas.restore(); } // 画对勾 private void drawtick(canvas canvas) { // 得到画对勾的进度 float temp = tickvalue * totallength; log.i(tag, "temp:" + temp + "downlength :" + downlength); //判断是否是刚开始画对勾的时候,即等于startpoint if (float.compare(tickvalue, 0f) == 0) { log.i(tag, "startpoint : " + startpoint.x + ", " + startpoint.y); path.reset(); path.moveto(startpoint.x, startpoint.y); } // 如果画对勾的进度已经超过breakpoint的时候,即(breakpoint,endpoint] if (temp > downlength) { path.moveto(startpoint.x, startpoint.y); path.lineto(breakpoint.x, breakpoint.y); log.i(tag, "endpoint : " + endpoint.x + ", " + endpoint.y); path.lineto((endpoint.x - breakpoint.x) * (temp - downlength) / uplength + breakpoint.x, (endpoint.y - breakpoint.y) * (temp - downlength) / uplength + breakpoint.y); } else { //画对勾的进度介于startpoinit和breakpoint之间,即(startpoint,breakpoint] log.i(tag, "down x : " + (breakpoint.x - startpoint.x) * temp / downlength + ",down y: " + (breakpoint.y - startpoint.y) * temp / downlength); path.lineto((breakpoint.x - startpoint.x) * temp / downlength + startpoint.x, (breakpoint.y - startpoint.y) * temp / downlength + startpoint.y); } canvas.drawpath(path, tickpaint); } // 画边框 private void drawborder(canvas canvas) { float temp; // 通过animatedvalue让边框产生一个“overshooting”的动画 if (animatedvalue > 1f) { temp = animatedvalue * mradius; } else { temp = mradius; } canvas.drawcircle(center, center, temp, borderpaint); } // 画checkbox内部 private void drawtrim(canvas canvas) { canvas.drawcircle(center, center, (mradius - mstrokewidth) * animatedvalue, trimpaint); }
ondraw(canvas canvas)代码中的逻辑基本都加了注释,主要就是原理搞懂了就比较简单了。在绘制对勾时要区分当前处于绘制对勾的哪种状态,然后对应做处理画出线条,剩下的就简单了。关于smoothcheckbox的讲解到这里就差不多了。
下面就贴出smoothcheckbox的完整代码:
public class smoothcheckbox extends view implements view.onclicklistener { // 动画持续时间 private long duration; // 边框宽度 private float mstrokewidth; // 对勾宽度 private float mtickwidth; // 内饰画笔 private paint trimpaint; // 边框画笔 private paint borderpaint; // 对勾画笔 private paint tickpaint; // 默认边框宽度 private float defaultstrikewidth; // 默认对勾宽度 private float defaulttickwidth; // 宽度 private int mwidth; // 高度 private int mheight; // 边框颜色 private int bordercolor; // 内饰颜色 private int trimcolor; // 对勾颜色 private int tickcolor; // 半径 private int mradius; // 中心点 private int center; // 是否是选中 private boolean ischecked; //对勾向下的长度 private float downlength; //对勾向上的长度 private float uplength; // 对勾的总长度 private float totallength; // 监听器 private oncheckedchangelistener listener; private valueanimator mvalueanimator; private valueanimator mtickvalueanimator; private float animatedvalue; private float tickvalue; // 对勾开始点 private point startpoint = new point(); // 对勾转折点 private point breakpoint = new point(); // 对勾结束点 private point endpoint = new point(); private static final string tag = "smoothcheckbox"; private static final string key_instance_state = "instancestate"; private path path = new path(); public void setoncheckedchangelistener(oncheckedchangelistener listener) { this.listener = listener; } public smoothcheckbox(context context) { this(context, null); } public smoothcheckbox(context context, attributeset attrs) { this(context, attrs, 0); } public smoothcheckbox(context context, attributeset attrs, int defstyleattr) { super(context, attrs, defstyleattr); typedarray a = getcontext().obtainstyledattributes(attrs, r.styleable.smoothcheckbox); duration = a.getint(r.styleable.smoothcheckbox_duration, 600); defaultstrikewidth = typedvalue.applydimension(typedvalue.complex_unit_dip, 1, getresources().getdisplaymetrics()); mstrokewidth = a.getdimension(r.styleable.smoothcheckbox_strikewidth, defaultstrikewidth); defaulttickwidth = typedvalue.applydimension(typedvalue.complex_unit_dip, 2, getresources().getdisplaymetrics()); mtickwidth = a.getdimension(r.styleable.smoothcheckbox_tickwidth, defaulttickwidth); bordercolor = a.getcolor(r.styleable.smoothcheckbox_bordercolor, getresources().getcolor(android.r.color.darker_gray)); trimcolor = a.getcolor(r.styleable.smoothcheckbox_trimcolor, getresources().getcolor(android.r.color.holo_green_light)); tickcolor = a.getcolor(r.styleable.smoothcheckbox_tickcolor, getresources().getcolor(android.r.color.white)); a.recycle(); trimpaint = new paint(paint.anti_alias_flag); trimpaint.setstyle(paint.style.fill); trimpaint.setcolor(trimcolor); borderpaint = new paint(paint.anti_alias_flag); borderpaint.setstrokewidth(mstrokewidth); borderpaint.setcolor(bordercolor); borderpaint.setstyle(paint.style.stroke); tickpaint = new paint(paint.anti_alias_flag); tickpaint.setcolor(tickcolor); tickpaint.setstyle(paint.style.stroke); tickpaint.setstrokecap(paint.cap.round); tickpaint.setstrokewidth(mtickwidth); setonclicklistener(this); } @override protected void onmeasure(int widthmeasurespec, int heightmeasurespec) { super.onmeasure(widthmeasurespec, heightmeasurespec); int widthsize = measurespec.getsize(widthmeasurespec); int widthmode = measurespec.getmode(widthmeasurespec); if (widthmode == measurespec.exactly) { mwidth = widthsize; } else { mwidth = 40; } int heightsize = measurespec.getsize(heightmeasurespec); int heightmode = measurespec.getmode(heightmeasurespec); if (heightmode == measurespec.exactly) { mheight = heightsize; } else { mheight = 40; } setmeasureddimension(mwidth, mheight); int size = math.min(mwidth, mheight); center = size / 2; mradius = (int) ((size - mstrokewidth) / 2 / 1.2f); startpoint.set(center * 14 / 30, center * 28 / 30); breakpoint.set(center * 26 / 30, center * 40 / 30); endpoint.set(center * 44 / 30, center * 20 / 30); downlength = (float) math.sqrt(math.pow(startpoint.x - breakpoint.x, 2f) + math.pow(startpoint.y - breakpoint.y, 2f)); uplength = (float) math.sqrt(math.pow(endpoint.x - breakpoint.x, 2f) + math.pow(endpoint.y - breakpoint.y, 2f)); totallength = downlength + uplength; } @override protected void ondraw(canvas canvas) { super.ondraw(canvas); canvas.save(); drawborder(canvas); drawtrim(canvas); if (ischecked) { drawtick(canvas); } canvas.restore(); } @override protected parcelable onsaveinstancestate() { bundle bundle = new bundle(); bundle.putparcelable(key_instance_state, super.onsaveinstancestate()); bundle.putboolean(key_instance_state, ischecked); return bundle; } @override protected void onrestoreinstancestate(parcelable state) { if (state instanceof bundle) { bundle bundle = (bundle) state; boolean ischecked = bundle.getboolean(key_instance_state); setchecked(ischecked); super.onrestoreinstancestate(bundle.getparcelable(key_instance_state)); return; } super.onrestoreinstancestate(state); } // 切换状态 private void toggle() { ischecked = !ischecked; if (listener != null) { listener.oncheckedchanged(this, ischecked); } if (ischecked) { checkedanimation(); } else { uncheckedanimation(); } } // 由未选中到选中的动画 private void checkedanimation() { animatedvalue = 0f; tickvalue = 0f; mvalueanimator = valueanimator.offloat(0f, 1.2f, 1f).setduration(2 * duration / 5); mvalueanimator.setinterpolator(new acceleratedecelerateinterpolator()); mtickvalueanimator = valueanimator.offloat(0f, 1f).setduration(3 * duration / 5); mtickvalueanimator.setinterpolator(new linearinterpolator()); mtickvalueanimator.addupdatelistener(new valueanimator.animatorupdatelistener() { @override public void onanimationupdate(valueanimator valueanimator) { tickvalue = (float) valueanimator.getanimatedvalue(); postinvalidate(); } }); mvalueanimator.addupdatelistener(new valueanimator.animatorupdatelistener() { @override public void onanimationupdate(valueanimator valueanimator) { animatedvalue = (float) valueanimator.getanimatedvalue(); postinvalidate(); } }); mvalueanimator.addlistener(new animatorlisteneradapter() { @override public void onanimationend(animator animation) { mtickvalueanimator.start(); log.i(tag," mtickvalueanimator.start();"); } }); mvalueanimator.start(); } // 由选中到未选中的动画 private void uncheckedanimation() { animatedvalue = 0f; mvalueanimator = valueanimator.offloat(1f, 0f).setduration(2 * duration / 5); mvalueanimator.setinterpolator(new accelerateinterpolator()); mvalueanimator.addupdatelistener(new valueanimator.animatorupdatelistener() { @override public void onanimationupdate(valueanimator valueanimator) { animatedvalue = (float) valueanimator.getanimatedvalue(); postinvalidate(); } }); mvalueanimator.start(); } // 画对勾 private void drawtick(canvas canvas) { float temp = tickvalue * totallength; log.i(tag, "temp:" + temp + "downlength :" + downlength); if (float.compare(tickvalue, 0f) == 0) { log.i(tag, "startpoint : " + startpoint.x + ", " + startpoint.y); path.reset(); path.moveto(startpoint.x, startpoint.y); } if (temp > downlength) { path.moveto(startpoint.x, startpoint.y); path.lineto(breakpoint.x, breakpoint.y); log.i(tag, "endpoint : " + endpoint.x + ", " + endpoint.y); path.lineto((endpoint.x - breakpoint.x) * (temp - downlength) / uplength + breakpoint.x, (endpoint.y - breakpoint.y) * (temp - downlength) / uplength + breakpoint.y); } else { log.i(tag, "down x : " + (breakpoint.x - startpoint.x) * temp / downlength + ",down y: " + (breakpoint.y - startpoint.y) * temp / downlength); path.lineto((breakpoint.x - startpoint.x) * temp / downlength + startpoint.x, (breakpoint.y - startpoint.y) * temp / downlength + startpoint.y); } canvas.drawpath(path, tickpaint); } // 画边框 private void drawborder(canvas canvas) { float temp; if (animatedvalue > 1f) { temp = animatedvalue * mradius; } else { temp = mradius; } canvas.drawcircle(center, center, temp, borderpaint); } // 画checkbox内部 private void drawtrim(canvas canvas) { canvas.drawcircle(center, center, (mradius - mstrokewidth) * animatedvalue, trimpaint); } @override public void onclick(view view) { toggle(); } /** * 判断checkbox是否选中状态 * * @return */ public boolean ischecked() { return ischecked; } /** * 设置checkbox的状态 * * @param ischecked 是否选中 */ public void setchecked(boolean ischecked) { this.setchecked(ischecked, false); } /** * 设置checkbox的状态 * * @param ischecked 是否选中 * @param isanimation 切换时是否有动画 */ public void setchecked(boolean ischecked, boolean isanimation) { this.ischecked = ischecked; if (isanimation) { if (ischecked) { checkedanimation(); } else { uncheckedanimation(); } } else { animatedvalue = ischecked ? 1f : 0f; tickvalue = 1f; invalidate(); } if (listener != null) { listener.oncheckedchanged(this, ischecked); } } public interface oncheckedchangelistener { void oncheckedchanged(smoothcheckbox smoothcheckbox, boolean ischecked); } }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。
上一篇: Android事件的分发机制详解