我们都知道正弦曲线的表达式为y=Asin(ωx+φ)+k,所以,在该demo中,我自定义一个view,在view的onDraw函数里手动绘制波浪效果的正弦函数,根据x坐标和正弦曲线表达式获取y坐标,此时y=10 * Math.sin((i + angle) * Math.PI / 180) + 20;
主要代码:
@Override
public void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
int height = getHeight();
int width = getWidth();
paint1.setColor(Color.rgb(205, 243, 246));
paint2.setAlpha(200);
paint2.setColor(Color.rgb(150, 206, 231));
paint3.setAlpha(150);
paint3.setColor(Color.rgb(89, 186, 231));
double lineX = 0;
double lineY1 = 0;
double lineY2 = 0;
double lineY3 = 0;
for (int i = 0; i < width; i++) {
lineX = i;
if (isRun) {
lineY1 = Math.sin((i + angle) * Math.PI / 180);
lineY2 = 10 * Math.sin((i + angle) * Math.PI / 180) + 20;
lineY3 = 20 * Math.sin((i + angle) * Math.PI / 180) + 50;
} else {
lineY1 = 0;
lineY2 = 20;
lineY3 = 50;
}
canvas.drawLine((int) lineX, (int) (lineY1 + height / 1.5),
(int) lineX + 1, (int) (lineY2 + height / 1.5), paint1);
canvas.drawLine((int) lineX, (int) (lineY2 + height / 1.5),
(int) lineX + 1, (int) (lineY3 + height / 1.5), paint2);
canvas.drawLine((int) lineX, (int) (lineY3 + height / 1.5),
(int) lineX + 1, height, paint3);
}
}
开启线程进行每隔1毫毛angle+1,当angle为360的时候,设置angle为0:
@Override
public void run() {
// TODO Auto-generated method stub
while (isRun) {
angle++;
if (angle == 360) {
angle = 0;
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void start() {
isRun = true;
new Thread(this).start();
}
public void stop() {
isRun = false;
angle = 0;
}