自定义SwitchView升级版
效果图:
在上一片文章中,我们只是在ACTION_MOVE中有动画效果,在这一片中,我们会在ACTION_DOWN和ACTION_UP中带有动画。
分析
关于自定义的属性和初始化那些,跟上一篇文章类似,假如你还没有阅读,请先阅读上一篇文章:自定义有动画的Switch控件
我们现在需要处理的是down和up事件,我们就需要添加一些属性去标记,比如down的位置,up之后应该是去到那里,每次重绘的spec是多少。所以我们添加了如下一些属性:
/**
* 动画结束的位置
*/
private float animEnd;
/**
* 每次更新的长度
*/
private float perAnim;
/**
* 分开5次更新
*/
private static final int SEPARATION_LENGHT = 5;//分开五次更新
/**
* 是否有动画
*/
private boolean hasAnim;
/**
* 动画方向,true为向右,false为向左
*/
private boolean animDirection;
实现
在drawCircle中去判断时候需要重绘动画
/**
* 画圆
*
* @param canvas
* @param isChecked
*/
private void drawCircle(Canvas canvas, boolean isChecked) {
@ColorInt int currentColor = isChecked ? enableCircleColor : disCircleColor;
mPaint.setColor(currentColor);
mPaint.setStyle(Paint.Style.FILL);
canvas.drawCircle(circleX, circleY, radius, mPaint);
if (hasAnim) {
drawWithAnim();
}
}
/**
* 画动画
*/
private void drawWithAnim() {
postDelayed(new Runnable() {
@Override
public void run() {
//右动画
if (animDirection) {
if (circleX + perAnim >= animEnd) { //是否到终点
circleX = animEnd;
hasAnim = false;
} else {
circleX += perAnim;
}
} else { //左动画
if (circleX - perAnim <= animEnd) {//是否到终点
circleX = animEnd;
hasAnim = false;
} else {
circleX -= perAnim;
}
}
update();
}
}, 20);// 20ms画一次
}
那么,我们再down的时候怎么判断时候需要动画呢?逻辑是:
1. 首先这个点action假如是在圆里面则没有动画
2. 假如是在圆的右边,则是右动画,需要注意判断时候超出边界
3. 假如是在圆的左边则是左动画,需要注意不要超出边界
代码如下
/**
* 是否有按下动画
*
* @param x
* @return
*/
private boolean calculateDownAnim(float x) {
if (x >= circleX - radius && x <= circleX + radius) {
if (x <= radius) {//在边界
circleX = radius;
} else if (x + radius >= width) { //在边界
circleX = (width - radius);
} else {
circleX = x;
}
return false;
}
perAnim = Math.abs(animEnd - circleX)/SEPARATION_LENGHT;
animDirection = isChecked;
// 计算动画起始位置和每次长度
if (x > circleX + radius) { // 右动画
if (x >= width - radius) {
animEnd = width - radius;
} else {
animEnd = x;
}
} else { //左动画
if (x < radius) {
animEnd = radius;
} else {
animEnd = x;
}
}
return true;
}
对于up事件则是比较简单,因为他的end位置只有两种,一个是circleX为radius,一个circleX为width-radius,然后默认up都是带有动画的就好,所以判断如下:
/**
* 是否有结束动画
*
* @param x
* @return
*/
private boolean calculateUpAnim(float x) {
// 如果在边界
animEnd = hasHalfWidth(x) ? width - radius : radius;
perAnim = Math.abs(animEnd - circleX) / SEPARATION_LENGHT;
animDirection = isChecked;
return true;
}
这样子,我们就完成了整一个带有移动动画的SwitchView控件了。
源码下载,求星星,star