我正在使用Surfaceview更改背景图像。但是我在holder.getSurface()。isValid()上弄错了,我也不知道为什么。我在这里查看了一些类似的问题,但仍然无法解决。到目前为止,我所做的工作是否缺少某些内容,还是应该尝试其他内容?
谢谢
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class BrickSmasherView extends SurfaceView {
SurfaceHolder holder;
Canvas canvas;
Context context;
Thread back = null;
volatile boolean running = false;
public BrickSmasherView(Context context) {
super(context);
this.context = context;
holder = getHolder();
}
public void runbackThread(){
back = new Thread(new Runnable() {
@Override
public void run() {
while (running){
draw();
}
}
});
back.start();
}
public void resumegame(){
running = true;
runbackThread();
}
public void pausegame(){
running = false;
try
{
back.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void draw(){
if(holder.getSurface().isValid()){
canvas = holder.lockCanvas();
canvas.drawBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.sky),0,0,null);
holder.unlockCanvasAndPost(canvas);
}
}
}
最佳答案
您必须在Callback
中添加SurfaceView
来接收有关Surface可用性的事件并从线程进行绘制。
回调示例将如下所示:
public class MyCallback implements SurfaceHolder.Callback {
@Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// you need to start your drawing thread here
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// and here you need to stop it
}
}
而且,您需要将此回调设置为SurfaceHolder:
surface.getHolder().addCallback(new MyCallback());
请尝试一下。我认为它将为您提供帮助
关于android - holder.getSurface()。isValid()返回false,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47669143/