思路参考https://github.com/zhongbaitu/WaveLoadingView,
只是自己动手实现,当作练手。
![](https://img.haomeiwen.com/i2035980/6246d72e9fda9500.gif)
<pre>
public class CustomWaveLoadingView extends View
{
private Paint mWavePaint;
private int mWaveColor = 0xff0099CC;
private Path path;
// 左右偏移 φ
private int fai = 0;
// 上下偏移
private volatile float k = -50;
// 角速度
private float w = 0.5f;
// 振幅
private int a = 20;
//控件高
private int mViewHeight;
//控件宽
private int mViewWidth;
//目标高度
private float mTargetHeight;
// 0% 时,空白的高度
private float mBaseBlank;
// 绘制间隔时间
private int mInterval = 4;
//是否继续绘制
private volatile boolean mIsRun = true;
//是否初始化
private boolean mIsFirst = true;
Runnable mDrawAuto = new Runnable()
{
@Override
public void run()
{
while (mIsRun)
{
fai++;
if (fai == 360)
{
fai = 0;
}
if (k > mTargetHeight)
{
k--;
}
mDrawHandler.sendEmptyMessage(1);
try
{
Thread.sleep(mInterval);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
Handler mDrawHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
invalidate();
super.handleMessage(msg);
}
};
public CustomWaveLoadingView(Context context)
{
this(context, null);
}
public CustomWaveLoadingView(Context context, AttributeSet attrs)
{
this(context, attrs, 0);
}
public CustomWaveLoadingView(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
init();
}
private void init()
{
//初始化波浪画笔
mWavePaint = new Paint();
mWavePaint.setAntiAlias(true);
mWavePaint.setColor(mWaveColor);
path = new Path();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
initData();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom)
{
super.onLayout(changed, left, top, right, bottom);
}
private void initData()
{
if (mIsFirst)
{
mViewWidth = getMeasuredWidth();
mViewHeight = getMeasuredHeight();
mBaseBlank = (float) (mViewHeight * 0.9);
mTargetHeight = (float) (mBaseBlank * 0.2);
k = mBaseBlank;
new Thread(mDrawAuto).start();
mIsFirst = false;
}
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
setPath();
canvas.drawPath(path, mWavePaint);
}
private void setPath()
{
path.reset();
int x = 0;
int y = 0;
for (int i = 0; i < mViewWidth; i++)
{
x = i;
y = (int) (a * Math.sin((i * w + fai) * Math.PI / 180) + k);
if (i == 0)
{
path.moveTo(x, y);
}
path.quadTo(x, y, x + 1, y);
}
path.lineTo(mViewWidth, mViewHeight);
path.lineTo(0, mViewHeight);
path.close();
}
}
</code></pre>
网友评论