如何创建一个surfaceview
时间: 2023-05-26 07:06:59 浏览: 73
自定义SurfaceView代码
要创建一个SurfaceView,你需要创建一个自定义视图类,并在其中添加SurfaceHolder。以下是创建SurfaceView的步骤:
1.创建一个继承自SurfaceView的自定义视图类:
```
public class MySurfaceView extends SurfaceView {
public MySurfaceView(Context context) {
super(context);
}
public MySurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MySurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
```
2.在自定义视图类中添加SurfaceHolder变量:
```
private SurfaceHolder surfaceHolder;
```
3.在构造函数中实例化SurfaceHolder:
```
public MySurfaceView(Context context) {
super(context);
surfaceHolder = getHolder();
}
```
4.实现SurfaceHolder.Callback接口:
```
public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback {
public MySurfaceView(Context context) {
super(context);
surfaceHolder = getHolder();
surfaceHolder.addCallback(this);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
```
5.在surfaceCreated方法中开启线程:
```
@Override
public void surfaceCreated(SurfaceHolder holder) {
new MyThread().start();
}
private class MyThread extends Thread {
@Override
public void run() {
while (true) {
Canvas canvas = surfaceHolder.lockCanvas();
// 进行绘制操作
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
```
6.在自定义视图中绘制图形
```
@Override
public void run() {
while (true) {
Canvas canvas = surfaceHolder.lockCanvas();
Paint paint = new Paint();
canvas.drawCircle(100, 100, 50, paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
```
这样,你就创建了一个SurfaceView,并且在其中绘制了一个圆。
阅读全文