如何用surfaceview绘制正弦波
时间: 2023-05-26 21:07:01 浏览: 96
以下是一个用SurfaceView绘制正弦波的例子:
1. 创建一个继承自SurfaceView的类,重写它的surfaceCreated、surfaceChanged和surfaceDestroyed方法。
```
public class SinWaveView extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mSurfaceHolder;
private DrawThread mDrawThread;
public SinWaveView(Context context, AttributeSet attrs) {
super(context, attrs);
mSurfaceHolder = getHolder();
mSurfaceHolder.addCallback(this);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mDrawThread = new DrawThread(holder);
mDrawThread.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mDrawThread.exit();
}
private class DrawThread extends Thread {
private SurfaceHolder mHolder;
private boolean mRunning = true;
public DrawThread(SurfaceHolder holder) {
mHolder = holder;
}
@Override
public void run() {
while (mRunning) {
Canvas canvas = null;
try {
canvas = mHolder.lockCanvas();
drawSinWave(canvas);
} finally {
if (canvas != null) {
mHolder.unlockCanvasAndPost(canvas);
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void exit() {
mRunning = false;
}
}
private void drawSinWave(Canvas canvas) {
int width = getWidth();
int height = getHeight();
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStrokeWidth(5);
paint.setStyle(Paint.Style.STROKE);
Path path = new Path();
float y;
float centerY = height / 2;
for (int x = 0; x < width; x++) {
y = (float) (Math.sin(Math.toRadians(x * 3)) * 50 + centerY);
if (x == 0) {
path.moveTo(0, y);
} else {
path.lineTo(x, y);
}
}
canvas.drawPath(path, paint);
}
}
```
2. 在surfaceCreated方法中启动一个DrawThread线程,用于不断地绘制正弦波。
3. 在DrawThread线程中使用SurfaceHolder.lockCanvas获取Canvas对象,并在Canvas上调用自定义的drawSinWave方法绘制正弦波。
4. parseSinWave方法利用Path对象和Math.sin函数绘制正弦波曲线,其中Math.sin的参数为角度。
阅读全文