Android drawBitmap position parameters

JrL picture JrL · Jul 26, 2012 · Viewed 7.7k times · Source

I am new to android graphic programming. I want to put a bitmap in the centre of my canvas. Hence, i use :

public void onDraw(Canvas canvas) {
    float canvasx = (float) canvas.getWidth();
    float canvasy = (float) canvas.getHeight();

Then i call the bitmap i want to use,

Bitmap myBitmap = BitmapFactory.decodeResource(getResources(),
        R.drawable.myBitmap);

Then i find the coordinate location for my bitmap by using these,

float bitmapx = (float) myBitmap.getWidth();
float bitmapy = (float) myBitmap.getHeight();

float boardPosX = (canvasx - bitmapx) / 2;
float boardPosY = (canvasy - bitmapy) / 2;

Finally, i draw the bitmap using,

canvas.drawBitmap(myBitmap, boardPosX, boardPosY, null);

But, the bitmap is not in the center of the canvas. It's a little bit below the position which i reckon should be the center of the canvas.

Is it correct to get the canvas height and width inside the onDraw() method ? Any idea what's wrong ? Thanks in advance.

*Edit :

Finally, i make it work by changing

public void onDraw(Canvas canvas) {
    float canvasx = (float) canvas.getWidth();
    float canvasy = (float) canvas.getHeight();

to

public void onDraw(Canvas canvas) {
    float canvasx = (float) getWidth();
    float canvasy = (float) getHeight();

However, i dont know why the change fixes my problem.

Answer

Todd Davies picture Todd Davies · Jul 26, 2012

Use this:

float boardPosX = ((canvasx/2) - (bitmapx / 2));
float boardPosY = ((canvasy/2) - (bitmapy / 2));