Android drawBitmap position parameters

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(),

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();


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

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


Use this:

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

private int mWidth;
private int mHeight;
private float mAngle;

@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    mWidth = View.MeasureSpec.getSize(widthMeasureSpec);
    mHeight = View.MeasureSpec.getSize(heightMeasureSpec);

    setMeasuredDimension(mWidth, mHeight);

@Override protected void onDraw(Canvas canvas)
    Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.compass);

    // Here's the magic. Whatever way you do it, the logic is:
    // space available - bitmap size and divide the result by two.
    // There must be an equal amount of pixels on both sides of the image.
    // Therefore whatever space is left after displaying the image, half goes to
    // left/up and half to right/down. The available space you get by subtracting the
    // image's width/height from the screen dimensions. Good luck.

    int cx = (mWidth - myBitmap.getWidth()) >> 1; // same as (...) / 2
    int cy = (mHeight - myBitmap.getHeight()) >> 1;

    if (mAngle > 0) {
        canvas.rotate(mAngle, mWidth >> 1, mHeight >> 1);

    canvas.drawBitmap(myBitmap, cx, cy, null);

Need Your Help

Reloading a TableView's data?

objective-c tableview xcode4.3

I'm trying to build a hello world application with Xcode 4.3.