Android开发仿IOS滑动开关实现代码
程序员文章站
2023-11-17 08:32:34
android开发仿ios滑动开关实现代码
android与ios相比,ios好多控件都是自带的,而android需要使用自定义来实现。今天说的是ios的滑动开关,我层看...
android开发仿ios滑动开关实现代码
android与ios相比,ios好多控件都是自带的,而android需要使用自定义来实现。今天说的是ios的滑动开关,我层看到好多博客都是通过自定义togglebutton实现的。这里我通过自定义view来实现他的效果。
首先在onsizechange里把2个半圆和一个矩形绘制出来。
width = w; height = h; left = top = 0; right = width; bottom = height * 0.8f; cx = (right + left) / 2; cy = (bottom + top) / 2; rectf rectf = new rectf(left, top, bottom, bottom); path.arcto(rectf, 90, 180); rectf.left = right - bottom; rectf.right = right; path.arcto(rectf, 270, 180); path.close(); circle_left = 0; circle_right = bottom; circle_width = circle_right - circle_left; float circle_height = (bottom - top) / 2; radius = circle_height * 0.9f; borderwidth = (int) (2 * (circle_height - radius)); circle_cx = width - circle_height;
剩下的就是ondraw方法来绘制颜色,以及切换的效果。
protected void ondraw(canvas canvas) { super.ondraw(canvas); paint.setstyle(style.fill); paint.setantialias(true); canvas.setdrawfilter(new paintflagsdrawfilter(0, paint.anti_alias_flag | paint.filter_bitmap_flag)); if (ischoose) { paint.setcolor(oncolor); } else { paint.setcolor(offcolor); } canvas.drawpath(path, paint); isanimation = isanimation - 0.1f > 0 ? isanimation - 0.1f : 0; //缩放大小参数随isanimation变化而变化 final float scale = 0.98f * (ischoose ? isanimation : 1 - isanimation); //保存canvas状态 canvas.save(); canvas.scale(scale, scale, circle_cx, cy); paint.setcolor(offcolor); canvas.drawpath(path, paint); canvas.restore(); paint.reset(); float btranslatex = width - circle_width; final float translate = btranslatex * (ischoose ? 1 - isanimation : isanimation); canvas.translate(translate, 0); if (isanimation > 0) { invalidate(); } canvas.save(); paint.setstyle(style.fill); paint.setcolor(offcolor); canvas.drawcircle(circle_width / 2, circle_width / 2, radius, paint); // 按钮白底 paint.setstyle(style.stroke); paint.setcolor(bordercolor); paint.setstrokewidth(borderwidth); canvas.drawcircle(circle_width / 2, circle_width / 2, radius, paint); // 按钮灰边 canvas.restore(); }
最后我们在ontouch里面去改变他的状态:
public boolean ontouchevent(motionevent event) { switch (event.getaction()) { case motionevent.action_down: return true; case motionevent.action_cancel: return true; case motionevent.action_up: isanimation = 1; ischoose = !ischoose; listener.onstatechanged(ischoose); invalidate(); break; } return super.ontouchevent(event); }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
上一篇: 判断点与圆的位置关系
下一篇: 字符串与各种集合类的相互转化