我做了一个应用程序来设置壁纸,我尝试了很多东西......真正对我有用的是这个方法:
// Crop or inflate bitmap to desired device height and/or width
public Bitmap prepareBitmap(final Bitmap sampleBitmap,
final WallpaperManager wallpaperManager) {
Bitmap changedBitmap = null;
final int heightBm = sampleBitmap.getHeight();
final int widthBm = sampleBitmap.getWidth();
final int heightDh = wallpaperManager.getDesiredMinimumHeight();
final int widthDh = wallpaperManager.getDesiredMinimumWidth();
if (widthDh > widthBm || heightDh > heightBm) {
final int xPadding = Math.max(0, widthDh - widthBm) / 2;
final int yPadding = Math.max(0, heightDh - heightBm) / 2;
changedBitmap = Bitmap.createBitmap(widthDh, heightDh,
Bitmap.Config.ARGB_8888);
final int[] pixels = new int[widthBm * heightBm];
sampleBitmap.getPixels(pixels, 0, widthBm, 0, 0, widthBm, heightBm);
changedBitmap.setPixels(pixels, 0, widthBm, xPadding, yPadding,
widthBm, heightBm);
} else if (widthBm > widthDh || heightBm > heightDh) {
changedBitmap = Bitmap.createBitmap(widthDh, heightDh,
Bitmap.Config.ARGB_8888);
int cutLeft = 0;
int cutTop = 0;
int cutRight = 0;
int cutBottom = 0;
final Rect desRect = new Rect(0, 0, widthDh, heightDh);
Rect srcRect = new Rect();
if (widthBm > widthDh) { // crop width (left and right)
cutLeft = (widthBm - widthDh) / 2;
cutRight = (widthBm - widthDh) / 2;
srcRect = new Rect(cutLeft, 0, widthBm - cutRight, heightBm);
} else if (heightBm > heightDh) { // crop height (top and bottom)
cutTop = (heightBm - heightDh) / 2;
cutBottom = (heightBm - heightDh) / 2;
srcRect = new Rect(0, cutTop, widthBm, heightBm - cutBottom);
}
final Canvas canvas = new Canvas(changedBitmap);
canvas.drawBitmap(sampleBitmap, srcRect, desRect, null);
} else {
changedBitmap = sampleBitmap;
}
return changedBitmap;
}
它来自本手册的代码,您将在其中找到更多正确调整图像大小的方法。