Canvas in android example

January 8, 2013 | Rishabh Agrawal | General

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. SurfaceView provides a dedicated drawing surface which can be set as the content view of any activity and Callback will 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;

public Preview(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 boolean var false

try {
thread.join();// destroy

} catch (InterruptedException e) {
//to do code

}
}
}

onDraw() will draw all the images,shapes,,text etc 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 aacording to the action you want to perform when these are called.

Step 3:

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

class PreviewThread extends Thread {
private boolean RunThread = 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©;

}
} 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©;
}

}
}
}//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 using this blog .


THE AUTHORRishabh Agrawal

Rishabh Agrawal is the founder of Creatiosoft, a company focused on creating high-quality software for the iGaming industry, specialising in poker and card games. With years of experience, Rishabh is dedicated to delivering engaging and user-friendly gaming experiences. Through this blog, he shares his passion and insights to help readers understand the latest trends and advancements in iGaming.

Recent Posts

The Future of Mobile Gaming: What to Expect in the Next 5 Years

Over the years, mobile gaming has seen amazing development and innovation utilized by the game development company in India. It…
06 Jun 2023 Rishabh Agrawal

How Do I Get Started With NFT Gaming?

The popularity of the NFT game has created a different fan base. There was a time when games were a…
18 Jul 2022 Rishabh Agrawal

What Are The Top Trends in NFT Marketplace 2022?

The NFTs are the new engaging and revolutionary technology across the globe. Though, these non-fungible tokens appeared for the first…
09 Jun 2022 Rishabh Agrawal