Tuesday, February 10, 2015

Android View vs SurfaceView - a deep dive


View 

If the application doesn’t require significant amount of processing or frame-rate speed (perhaps for a chess game, snake game, or another slowly-animated application), then developer can consider creating a custom view component and drawing with a Canvas in View.onDraw. 

This can be done by extending the View class and define the onDraw() callback method. this method will be called by the Android framework. Android framework will call the onDraw only as necessary. Each time application is prepared to draw something, then we should call the invalidate() method. 

One important thing to note is that, ignored to call invalidate from another thread than application’s UI thread, application should use the postInvalidate() method. 

Surface View
the surface view is a special subclass of View that offers a dedicated drawing surface within the view hierarchy. The aim is to offer this drawing surface to an applications secondary thread, so  that the application isn’t required to wait until the System’s view hierarchy is ready to draw. Instead, a secondary thread that has reference to the surface view can draw it to its own Canvas at its own pace. 

To begin using the SurfaceView, below are the tasks involved

1. Create a class that extends SurfaceView. 
2. Implement SurfaceHolder.Callback also in this class (this class gives the callback about when the surface is created, changed or destroyed)
3. Define thread class in this new Class that can be used for updating the surfaceview. 
4.Instead of handling surface object directly, Application should handle it via SurfaceHolder. application can get hold of this by calling getHolder method. then  add a listener using addCallback method .

Inorder to draw to the Surface Canvas from the secondary thread, applicant must pass the thread to the SurfaceHandler and call lockCanvas() then draw on to the canvas and once done with drawing, call the unlockCanvasAndPost() method passing the canvas object. 

References: 


No comments:

Post a Comment