Android水波纹效果
z真真 人气:0效果如下:
原理
控制代码
//这里用的kotlin //主线程刷新控件 val mHandler = object : Handler() { override fun handleMessage(msg: Message?) { waterRippleView.refreshView() } //开启动画,开线程,延时刷新period值,画布进行x方向平移 private fun progressAdd() { isAnimate = true Thread(Runnable { while (isAnimate) { Thread.sleep(100) mHandler.sendEmptyMessage(0) } }).start() } //停止动画 private fun progressReduce() { isAnimate = false }
控件源码:
//java编写 public class WaterRippleView extends View { private float mWidth; private float mHeight; //总周期为2s private int CIRCLE_PERIOD = 2000; //振幅,波纹高度 private float ampltitude = 100; //填充颜色 private int paintColor = 0xff57c011; //当前时间值,累加并循环 private int period = 0; private Paint paint; private Path path; public WaterRippleView(Context context) { this(context, null); } public WaterRippleView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public WaterRippleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); paint = new Paint(); paint.setColor(paintColor); paint.setStyle(Paint.Style.FILL); paint.setAntiAlias(true); path = new Path(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mWidth = w; mHeight = h; } public void refreshView() { period += 100; if (period > CIRCLE_PERIOD) period %= CIRCLE_PERIOD; invalidate(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //周期性的移动画布 float offsetX = mWidth / CIRCLE_PERIOD * period; canvas.translate(-offsetX, 0); path.reset(); //第一个正弦曲线 path.moveTo(0, mHeight / 2); path.cubicTo(mWidth / 4, mHeight / 2 - ampltitude, mWidth * 3 / 4, mHeight / 2 + ampltitude, mWidth, mHeight / 2); //第二个正弦曲线 path.cubicTo(mWidth * 5 / 4, mHeight / 2 - ampltitude, mWidth * 7 / 4, mHeight / 2 + ampltitude, 2 * mWidth, mHeight / 2); //形成闭合路径 path.lineTo(2 * mWidth, mHeight); path.lineTo(0, mHeight); path.lineTo(0, mHeight / 2); canvas.drawPath(path, paint); } }
加载全部内容