Canvas in android example

Canvas class along with SurfaceView class can be used to create a custom view easily for a game or a live wallpaper etc. So, if you want to make a custom view then let’s start learning how to use canvas.

Canvas class lets you create graphical effects .It provides the drawing methods to draw on a bitmap. It provides methods for drawing, e.g. drawARGB() for drawing a color, drawBitmap() to draw a Bitmap, drawText() to draw a text, drawRoundRect() to draw a rectangle with rounded corners etc .Here is a reference to all its methods.

The Paint class specifies how you draw on the bitmap.The Paint class allows specifying the color, font and certain effects for the drawing operation.

Step 1

Firstly we need a class that extends SurfaceView and implements SurfaceHolder.Callback.SurfaceViewprovides a dedicated drawing surface which can be set as the content view of any activity and Callbackwill allow you to be notified when the surface is created and destroyed, starting and stopping any current tasks.

 

public class Preview extends SurfaceView implements SurfaceHolder.Callback
{	private Context context;
private  PreviewThread thread;

publicPreview(Context context) {
	super(context);
this.context = context;
getHolder().addCallback(this);
thread = new PreviewThread(this);
//code	
}

getHolder().addCallback(this) lets us setup the Callback interface and use its functions.thread = new PreviewThread(this) creates the instance of thread class

Step 2:

In Preview class create the following functions:

// called from thread to draw on canvas
	public void onDraw(Canvas canvas) {
		
		this.canvas = canvas;
canvas.drawBitmap(bitmap,0,0),
//rest of images/shapes/text you want to draw on the canvas
		
}

public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
	//code
	}

	public void surfaceCreated(SurfaceHolder holder) {
		 //start the thread
		if (!thread.isAlive()) {
			thread = new PreviewThread(this);
		}

		thread.setRunning(true);
		thread.start();

	}

	public void surfaceDestroyed(SurfaceHolder holder) {

		//set the condition for stopping doDraw() calls from the thread 
thread.setRunning(false);// sets booleanvar false
		
			try {
				thread.join();// destroy
				
			} catch (InterruptedException e) {
				//to do code				

			}
		}
	}

onDraw() will draw all the images,shapes,,textetc on the canvas each time it is called from the thread at updated positions as set by the program for updating x and y positions .

surfaceChanged() notifies the change of surface,surfaceCreated() notifies creation of surface and surfaceDestroyed() notifies destruction of surface. Add required code in these functions aacordingto the  action you want to perform when these are called.

Step 3:

Create the PreviewThread calls that will extend Threadclass and calls the doDraw() of the Preview class.

classPreviewThread extends Thread {
		privatebooleanRunThread = false;
//constructor
PreviewThread(Context con)
{
 Context=con;
}

private Preview preview;
Context context;
	/*
	 *            Should the loop keep running?
	 */
	public void setRunning(boolean run) {
		mRunThread = run;

	}



/**
	 * Perform the game loop. 
	 */
	@Override
	public void run() {
	
		Canvas c = null;
		
while (mRunThread) {
updateCordinates();//function that updates x and y positions of views 
			try {
					c = preview.getHolder().lockCanvas(null);
					synchronized (preview.getHolder()) {

						
						if(c!=null)
						preview.onDraw(c);

					}
				} finally {
					// do this in a finally so that if an exception is thrown
					// during the above, we don't leave the Surface in an
					// inconsistent state
					if (c != null) {
						preview.getHolder().unlockCanvasAndPost(c);
					}

				}
		}
}//class


Step 4:

Set instance of Preview class as the content view of your activity.

public class GameActivity extends Activity {

	public Preview mPreview;
	

	/**
	 * Method called on application start.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		mPreview = new Preview(this);
		setContentView(mPreview); // game preview is a view
	}


This is it! Now you are ready for using Canvas and SurfaceView .Go ahead and make some great apps and games using this blog .

Advertisements