Monthly Archives: June 2012

Drawing with the Canvas object in Android

When writing an Android game one of the first things I had to start looking at is the methods provided for drawing. Being that I had no real purpose for developing a 3D game, I decided to go 2D. There are many things that a bitmap can do for you in regards to saving you development time, but the game platform that I am pursuing next did much better with mathematical drawing.

This brought me to searching out the object that I would use to display colorful shapes that I chose at specific window positions. The first object I have come across to do this is the Canvas. A Canvas can be accessed by overriding the OnDraw method of the Android View object. A View is an object that you place in your layout to indicate UI functionality. While there are many methods in the Canvas that work well for drawing, I focused in on two of them which were drawLine and drawRectangle.

In my example I went through a few iterations to figure out screen width and what I should do with it, but ultimately I started focusing in on using a percentage of the screen with as opposed to using hard coded numbers, as it scales better on landscape mode if you go back and forth between portrait. Ultimately I came up with a method that looks like this to draw a block on my game:

GamePieceBlock block = m_BoardBlocks.get(i);
block.getXPosition();
blockLeftSide = leftSide + (width / m_PiecesWide) * block.getXPosition();
blockRightSide = blockLeftSide + (width / m_PiecesWide);
Paint pnt = new Paint();
pnt.setColor(block.getColor());

blockBottomSide = bottomSide - (height / m_PiecesTall) * block.getYPosition();
blockTopSide = blockBottomSide - (height / m_PiecesTall);

m_Canvas.drawRect(blockLeftSide, blockTopSide, blockRightSide, blockBottomSide, pnt);

This method draws a solid block of color at the position that I calculated.  To get the m_Canvas instance I set it in my onDraw method and then call down to my game methods to draw the object on the canvas.  The other method that I use is the drawLine method which looks like this:

m_Canvas.drawLine(rightSide, bottomSide, rightSide, topSide, boardPaint);
m_Canvas.drawLine(rightSide + 1, bottomSide, rightSide + 1, topSide, boardPaint);