June 29, 2014

Working with 2D graphics

There are two ways to draw to the screen. Check below chart to find various ways to draw 2D graphics
  1. Draw to the view - Simple graphics with little or no updates
  2. Draw to a canvas - More complex graphics with regular updates
1. Draw to a view:
Let's first see how to draw to view. Drawing to view can be done using the Drawable objects like the ShapeDrawable, ColorDrawable and BitmapDrawable class. A simple way to draw a bitmap is shown in the xml file below
BitmapDrawable:
Any images can be drawn to a imageview as shown below
ShapeDrawable:
Following shapes can be drawn using the drawable class
Similar to Bitmaps, shapes can be drawn as shown below
Just like putting the image to be drawn in res/drawable folder, a shape can be defined manually using an xml and put in the res/drawable folder. Below is shown an example of how to define drawable shape.

Drawing to view is especially useful when setting background for buttons like shown below.

2. Draw to a canvas:
To draw using canvas you need 4 things. They are,
There are two ways to draw. 
*By extending View and overriding the onDraw() method - for less updates using internal thread as shown below

*By extending SurfaceView  and implementing the SurfaceHolder.Callback interface - for more updates
What is SurfaceView?
SurfaceViews need a separate, non-UI thread in which to do their work so their operations won't interfere with UI thread unlike the 'By extending View' shown above. A SurfaceView manages a low-level drawing area called a Surface. And this Surface is a dedicated drawing area, that is positioned within the applications view hierarchy. To define a SurfaceView, you need to create a custom class, which is a subclass of SurfaceView. And this custom class must, must also implement the SurfaceHolder.Callback interface. 
Setup of surfaceview:
>First use the SurfaceViews getHolder method to acquire the SurfaceView's SurfaceHolder. 
>Next, you register the SurfaceView for SurfaceHolder callbacks
Below code shows the callback methods where the thread which does the actual surface locking and other important housekeeping is handled is defined. This ensures less work on the UI thread.
Drawing on surfaceview:
>After the setup is done, draw using the canvas supplied by the lockCanvas() method.

No comments:

Post a Comment