Bitmap not showing up on canvas

1k Views Asked by At

I have canvas that I am drawing a bitmap on. I set the dimensions of the canvas and bitmap to variables and printed out their respective values. When I try to draw the bitmap it does not show up.

Code for SurfaceView:

protected void onDraw(Canvas canvas) {
    if (canvas != null) {
        canvas.drawColor(Color.WHITE);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        int canvasWidth = canvas.getWidth();
        int canvasHeight = canvas.getHeight();
        int memoryManiaWidth = memoryMania.getWidth();
        int memoryManiaHeight = memoryMania.getHeight();
        Rect src = new Rect(0,0,memoryManiaWidth,memoryManiaHeight);
        Rect dst = new Rect(0,0,canvasWidth,canvasWidth*(memoryManiaHeight/memoryManiaWidth));
        Log.d("MM","CW"+ String.valueOf(canvasWidth));
        Log.d("MM","MMH" + String.valueOf((memoryManiaHeight)));
        Log.d("MM","MMW" + String.valueOf((memoryManiaWidth)));
        Log.d("MM",String.valueOf(canvasWidth*(memoryManiaHeight/memoryManiaWidth)));
        canvas.drawBitmap(memoryMania,src,dst,paint);
    }

}

Logcat Output:

06-15 21:56:07.395  22939-23030/com.delg.andrew.memorymania D/MM﹕ CW1080
06-15 21:56:07.395  22939-23030/com.delg.andrew.memorymania D/MM﹕ MMH419
06-15 21:56:07.395  22939-23030/com.delg.andrew.memorymania D/MM﹕ MMW951
06-15 21:56:07.395  22939-23030/com.delg.andrew.memorymania D/MM﹕ 0

The bitmap displays if I change the bottom parameter of the dst Rect variable to anything but its present value. For example if i changed

dst = new Rect(.....,canvasWidth*(......));

to

dst = new Rect(.....,canvasWidth));

it will display.

As you can see in the logcat output,

canvasWidth*(memoryManiaHeight/memoryManiaWidth)

is evaluated to 0. Why is this happening and what can I do to fix it?

2

There are 2 best solutions below

0
On BEST ANSWER

Change your calculation from this:

canvasWidth*(memoryManiaHeight/memoryManiaWidth)

to this:

(canvasWidth*memoryManiaHeight)/memoryManiaWidth

If you evaluate (memoryManiaHeight/memoryManiaWidth) first then it will evaluate to zero due to integer division.

0
On

Is there any chance that the value of memoryManiaHeight is smaller than memoryManiaWidth? They are both integers, so zero produced. Try to check values of the two variables.And this should work:

(int) ( canvasWidth * ((float)memoryManiaHeight/memoryManiaWidth) );