Android drawing on surfaceview and canvas

前端 未结 3 652
清酒与你
清酒与你 2020-12-13 22:16

I have a \"simple\" problem. I try to draw on surfaceview. Layout-XML:



        
相关标签:
3条回答
  • 2020-12-13 22:53

    SurfaceView is composed by a View in your current layout and a surface under your layout. If you set a background to the view, you won't see anything of what is happening on the surface.

    0 讨论(0)
  • 2020-12-13 22:55

    Did you try

    yourHolder.unlockCanvassAndPost(your_canvas);
    
    0 讨论(0)
  • 2020-12-13 22:56

    Following Snippet will help you.

    public class SurfaceDemo extends Activity implements SurfaceHolder.Callback {
    
        private static final String TAG = "Svetlin SurfaceView";
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            SurfaceView view = new SurfaceView(this);
            setContentView(view);
            view.getHolder().addCallback(this);
        }
    
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            tryDrawing(holder);
        }
    
        @Override
        public void surfaceChanged(SurfaceHolder holder, int frmt, int w, int h) { 
            tryDrawing(holder);
        }
    
        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {}
    
        private void tryDrawing(SurfaceHolder holder) {
            Log.i(TAG, "Trying to draw...");
    
            Canvas canvas = holder.lockCanvas();
            if (canvas == null) {
                Log.e(TAG, "Cannot draw onto the canvas as it's null");
            } else {
                drawMyStuff(canvas);
                holder.unlockCanvasAndPost(canvas);
            }
        }
    
        private void drawMyStuff(final Canvas canvas) {
            Random random = new Random();
            Log.i(TAG, "Drawing...");
            canvas.drawRGB(255, 128, 128);
        }
    }
    
    0 讨论(0)
提交回复
热议问题