[我试图按比例缩小高分辨率图像,如1980x1080左右的尺寸,并且在nexus 5 API 21+中进行仿真,我需要将此高分辨率图像加载到我的图像视图支架中。
我正在使用下面的位图代码
float imageRatio = (float) newWidth / newHeight;
int imageWidth = mybitmapimage.getWidth();
int imageHeight = mybitmapimage.getHeight();
float aspectRatio = (float) imageWidth / imageHeight; // original iamge
// Initializing to find which needs scale down
float scaleWidth = newWidth;
float scaleHeight = newHeight;
if (imageRatio < aspectRatio) {
scaleHeight = ((float) newWidth) / aspectRatio;
} else {
scaleWidth = ((float) newHeight) * aspectRatio;
}
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(
bm, 0, 0, imageWidth, imageHeight, matrix, false);
return resizedBitmap;
为了我的一生,这段代码总是以拉伸或裁剪的方式结束。源图像文件大约为1920 * 1080,因此其尺寸会缩小。
[如果有人能帮助我解决这个棘手的问题,我将非常感激。
ratio = Math.min(newWidth/oldWidth, newHeight/oldHeight);
这就是在保持宽高比的同时获得缩放比例以调整位图大小的方法。
然后是最终的宽度和高度:
finalWidth = oldWidth * ratio;
finalHeight = oldHeight * ratio;
只需在比例矩阵中使用该比例:
matrix.postScale(ratio, ratio);