How to scale bitmaps to take the same percent of the screen with different screensizes and densities?

79 views Asked by At

I am trying to scale bitmaps on a canvas in Android.

What I currently am doing:

int scaleFactor = 0.01;
int size = screenWidth * screenHeight * scaleFactor;
Rect rect = new Rect(x,y, x + size, y + size);
canvas.drawBitmap(bitmap, null, rect, null);

The problem is that phones with lower density will show much smaller images than phones with higher density.

Does anyone know a tactic or solution to this?

1

There are 1 answers

0
Gaute-MO On BEST ANSWER

This is how i solved it.

Instead of calculating all the pixels on the screen in total, with screenWidth * screenHeight. I calculated the diagonal, and scaled all with a factor based to the diagonal length.

float x1 = 0; //left of screen
float y2 = 0; //top of screen
float x2 = screenWidth; //right of screen
float y2 = screenHeight; //bottom of screen
double distance = Math.sqrt(Math.pow(Math.abs(x1 - x2),2) + Math.pow(Math.abs(y1 - y2), 2));
int scaleFactor = 0.01;
int size = distance * scaleFactor;
Rect rect = new Rect(xPos,yPos, xPos + size, yPos + size);
canvas.drawBitmap(bitmap, null, rect, null);