Android实现炫酷的CheckBox效果

Android实现炫酷的CheckBox效果,第1张

概述首先贴出实现的效果图:gif的效果可能有点过快,在真机上运行的效果会更好一些。我们主要的思路就是利用属性动画来动态地画出选中状态以及对勾的绘制过程。看到上面的效果图,相信大家都迫不及待地要跃跃欲试了,那

首先贴出实现的效果图:

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):

@OverrIDeprotected 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)了:

@OverrIDeprotected 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,(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,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));  upLength = (float) Math.sqrt(Math.pow(endPoint.x - breakPoint.x,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,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.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.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 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,borderPaint); } // 画checkBox内部 private voID drawTrim(Canvas canvas) {  canvas.drawCircle(center,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实现炫酷的CheckBox效果全部内容,希望文章能够帮你解决Android实现炫酷的CheckBox效果所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1148004.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存