我需要在主屏幕上从图像中制作一个图标。我使用标准代码:
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
final int scaleFactor = (int) Math.max(photoW/app_icon_size, photoH/app_icon_size);
// Decode the image file into a Bitmap sized to fill needed sizes
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, bmOptions);
return bitmap;
但由于inSampleSize
使用整数而不是浮点数,我必须将位图缩小一点以使其完全符合我需要的尺寸:
final float aspectRatio = (float) bitmap.getWidth()/bitmap.getHeight();
final int finalW = (aspectRatio < 1 ? (int) (app_icon_size*aspectRatio) : app_icon_size);
final int finalH = (aspectRatio > 1 ? (int) (app_icon_size/aspectRatio) : app_icon_size);
bitmap = Bitmap.createScaledBitmap(bitmap, finalW, finalH, false);
一切都很好,它从0点开始缩放。所以我尝试使用createBitmap
与Matrix而不是createScaledBitmap
:
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale((float) finalW/bitmap.getWidth(), (float) finalH/bitmap.getHeight(), (float) bitmap.getWidth()/2, (float) bitmap.getHeight()/2);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), scaleMatrix, false);
但没有改变,它仍然从0,0扩展。这是一个平庸的问题,我想,但Stack和其他资源上的大多数解决方案都涉及Canvas和View,但我需要将Bitmap缩放为它。