surfaceview 刷新bitmap
时间: 2023-08-18 15:03:55 浏览: 102
要在 SurfaceView 中刷新 Bitmap,你需要在 SurfaceView 中创建一个绘制线程,然后在该线程中使用 Canvas 绘制 Bitmap。具体步骤如下:
1. 在 SurfaceView 中创建一个绘制线程:
```
class DrawThread extends Thread {
private SurfaceHolder surfaceHolder;
private boolean isRunning;
private Bitmap bitmap;
public DrawThread(SurfaceHolder surfaceHolder, Bitmap bitmap) {
this.surfaceHolder = surfaceHolder;
this.bitmap = bitmap;
isRunning = true;
}
public void setRunning(boolean running) {
isRunning = running;
}
@Override
public void run() {
while (isRunning) {
Canvas canvas = null;
try {
canvas = surfaceHolder.lockCanvas();
if (canvas != null) {
canvas.drawBitmap(bitmap, 0, 0, null);
}
} finally {
if (canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
}
```
2. 在 SurfaceView 中创建一个 SurfaceHolder.Callback 对象,实现 surfaceCreated() 方法,在该方法中启动绘制线程:
```
class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback {
private DrawThread drawThread;
private Bitmap bitmap;
public MySurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
getHolder().addCallback(this);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_bitmap);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
drawThread = new DrawThread(holder, bitmap);
drawThread.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
drawThread.setRunning(false);
while (retry) {
try {
drawThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
}
```
这样,每当你更新 Bitmap 的时候,就可以在绘制线程中重新绘制 Bitmap,从而实现 SurfaceView 中 Bitmap 的刷新。
阅读全文