日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Android自定義View實現簡單水波紋效果_Android

作者:z真真 ? 更新時間: 2022-10-13 編程語言

本文實例為大家分享了Android自定義View實現水波紋效果的具體代碼,供大家參考,具體內容如下

效果如下:

原理

控制代碼

//這里用的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);
? ? }
}

原文鏈接:https://blog.csdn.net/ZHENZHEN9310/article/details/94167669

欄目分類
最近更新