先不多说了,上个图
实现的思路看下图
如图,由两个完整的波组成,起始阶段左边的波不可见,右边的波可见。我们采用贝塞尔曲线画波,那么两个完整的波就包含9个点,我们可以定义两个长度为9的数组
private float[] mX;// x坐标点
private float[] mY;// y坐标
用来存储波运动过程中的点位。如图初始阶段我们这设置波的坐标为
初始化x轴坐标
private void initPointsX() {
for (int i = 0; i < mX.length; i++) {
// 从P0开始初始化到P4n+4,总共4n+5个点
mX[i] = i * mWaveWidth / 2 - mWaveWidth * 2;
}
}
初始化Y轴坐标,mLevelLine水平线,初始化时两个波都以控件底部边线作为水平线
private void initPointsY() {
mLevelLine = mRadius*2;
for (int i = 0; i < mX.length; i++) {
// 从P0开始初始化到P4n+4,总共4n+5个点
float y = 0;
switch (i % 4) {
case 0:
case 2:
y = mLevelLine;
break;
case 1:
y = mLevelLine + WAVEVALUE;//波峰或波谷
break;
case 3:
y = mLevelLine - WAVEVALUE;//波峰或波谷
break;
default:
break;
}
mY[i] = y;
}
}
好了我们开始画波了
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
drawWave(canvas);
mHandler.postDelayed(run, 5);
}
private void drawWave(Canvas canvas) {
mPaint.setColor(Color.BLUE);
mPaint.setStyle(Paint.Style.FILL);//封闭的图形
mPath.reset();
mPath.moveTo(mX[0], mY[0]);//以第一个作为起始点
for (int i = 0; i < mX.length - 2; i = i + 2) {
mPath.quadTo(mX[i + 1], mY[i + 1], mX[i + 2], mY[i + 2]);
}
mPath.lineTo(mX[mX.length-1], mRadius*2);
mPath.lineTo(mX[0], mRadius*2);
mPath.close();
canvas.drawPath(mPath, mPaint);
}
好了怎么让波动起来呢,还记得draw方法里面的mHandler.postDelayed(run, 5)
protected class MyRunnable implements Runnable {
@Override
public void run() {
if (mX[0] == 0) {
initPointsX();
} else if(mY[0] == 0) {
initPointsY();
}else {
movePoints();
}
postInvalidate();
}
}
给波的点加个水平和垂直的速度
private void movePoints() {
for (int i = 0; i < mX.length; i++) {
// 从P0开始初始化到P4n+4,总共4n+5个点
mX[i] = mX[i] + SPEEDX;
mY[i] = mY[i] - SPEEDY;
}
}
最终的效果
代码地址
http://download.csdn.net/download/gaopin_xianlu/10149065