如何缩放位图以在不同屏幕尺寸和密度下占据相同百分比的屏幕?

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

我正在尝试缩放 Android 中 canvas 上的位图。

我目前在做什么:

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

问题是密度较低的手机显示的图像比密度较高的手机小得多。

有人知道解决这个问题的策略或解决方案吗?

我就是这样解决的。

而不是计算屏幕上所有像素的总和,用screenWidth * screenHeight。我计算了对角线,并使用基于对角线长度的系数对所有进行缩放。

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