• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Draw chunked bitmap on Canvas using Matrix

tim687

Newbie
Apr 22, 2012
13
1
Hi developers,

Due to some unknown reason my previous attempt to post this question didn't succeed.

When a bitmap is loaded that exceeds the max texture size, my piece of code chunks up the image. That is working great,
but the drawing to the canvas isn't working that well. The position of the chunks aren't correct.

This is my code:
Code:
// This piece of code is executed in the constructor
if (widthPieces * chunkWidth <= canvasWidth && heightPieces * chunkHeight<= canvasHeight) {
scale = 1.0f;
} else {
scale = Math.min((float) canvasWidth / (float) (widthPieces * chunkWidth),
(float) canvasHeight / (float) (heightPieces * chunkHeight));
}
offsetX = ((canvasWidth - bitmapWidth)* scale) / 2;
offsetY = ((canvasHeight - bitmapHeight) * scale) / 2;


/**
*
* @param canvas The canvas that needs to be written to
* @param matrix Optional matrix to draw the bitmap
* @param paint Optional paint to draw the bitmap
* @return the canvas that has been written to
*/
public Canvas writeBitmapsToCanvas(Canvas canvas, Matrix matrix, @Nullable Paint paint){

for(int x =0; x < widthPieces; x++){
for(int y =0; y < heightPieces; y++){
// Scale the canvas to make sure that the image fits. Code copied from the ImageView class but heavily edited

matrix.postTranslate((x * chunkWidth * scale) + offsetX, (y * chunkHeight * scale) + offsetY);

matrix.preScale(scale, scale);

// End scaling and positioning

canvas.drawBitmap(bitmaps[x][y], matrix, paint);

}
}


Log.d("TooLargeBitmap", "Bitmaps written to the canvas!");
return canvas;

}

When I change (and remove this piece from the for statements)
Code:
canvas.drawBitmap(bitmaps[x][y], matrix, paint);
matrix.postTranslate((x * chunkWidth * scale) + offsetX, (y * chunkHeight * scale) + offsetY);

To
Code:
canvas.drawBitmap(bitmaps[0][0], matrix, paint);
matrix.postTranslate((0 * chunkWidth * scale) + offsetX, (0 * chunkHeight * scale) + offsetY);

The first chunk is drawn on the position where I want it to be. So I don't get the bug here when I put the piece back in the for statements using the x and y instead of the 0's

Here are some example values (not hardcoded):
Code:
bitmapHeight = 2160;
bitmapWidth = 4096;

widthPieces = 4;
heightPieces = 3;

chunkHeight = 1024;
chunkWidth = 720

canvasWidth = 720;
canvasHeight = 1280;

scale = 0,17578125;

Do I need to use postTranslate, preTranslate or setTranslate for this?

I need to use a matrix because the image can be rotated.

Thanks in advance for your help!

Tim
 

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones