简体   繁体   中英

Nothing Shows Up on Canvas from SurfaceHolder . lockCanvas() [Android]

I'm trying to draw on the canvas that is returned from the surface holder's . lockCanvas() function but the canvas that is rendered is simply white.

My MySurface extends SurfaceView and implements SurfaceHolder The constructor:

MySurface(Context context){
            super(context);
            surfaceHolder = getHolder();
            surfaceHolder.addCallback(this);
            displayThread = new MyDisplayThread(surfaceHolder);
        }

My surfaceCreated() override

public void surfaceCreated(SurfaceHolder sH){
            displayThread.start();
        }

My surfaceDestroyed() override

public void surfaceDestroyed(SurfaceHolder sH){
            boolean reset = true;
            while(reset){
                try{
                    displayThread.join();
                    reset = false;
                }catch (InterruptedException e){}
            }
        }

And the thread that I use for drawing: the class variables are:

SurfaceHolder surfaceHolder,
Paint paint,
boolean isRunning,
Canvas canvas = null


 class MyDisplayThread extends Thread {

        MyDisplayThread(SurfaceHolder sH){
            surfaceHolder = sH;
            isRunning = true;
            paint = new Paint();
        }

        @Override
        public void run(){
            while(isRunning){
                canvas = surfaceHolder.lockCanvas();
                try{
                    myDraw();
                }finally {
                    if(canvas != null) surfaceHolder.unlockCanvasAndPost(canvas);
                }
            }
        }

        public void myDraw(){
            paint.setARGB(255,152,54,12);
            canvas.drawText("RSFDS",100,100,paint);
            canvas.drawRect(120,150,300,300,paint);
            paint.setARGB(255,255,255,255);
        }
    }

Try the following (these have worked for me in the past):

Put setWillNotDraw(false); inside surfaceCreated

Call postInvalidate(); on your SurfaceHolder object before drawing each frame.

You need to call getHolder() again after surfaceCreated() is called. That should fix your problem.

@Override
public void surfaceCreated(SurfaceHolder holder) {
    surfaceHolder = getHolder();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM