我有一个大小为 1024x1024.png 的位图,我需要在不同的设备屏幕上拉伸它,我尝试使用这个:
// given a resource, return a bitmap with a specified maximum height
public static Bitmap maxHeightResourceToBitmap(Context c, int res,
int maxHeight) {
Bitmap bmp = imageResourceToBitmap(c, res, maxHeight);
int width = bmp.getWidth();
int height = bmp.getHeight();
int newHeight = maxHeight;
int newWidth = maxHeight / 2;
// calculate the scale - in this case = 0.4f
float scaleHeight = ((float) newHeight) / height;
float scaleWidth = ((float) newWidth) / width;
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap and return it
return Bitmap.createBitmap(bmp, 0, 0, width, height, matrix, true);
}
// given a resource, return a bitmap with a specified maximum height
public static Bitmap scaleWithRatio(Context c, int res,
int max) {
Bitmap bmp = imageResourceToBitmap(c, res, max);
int width = bmp.getWidth();
int height = bmp.getHeight();
// calculate the scale - in this case = 0.4f
float scaleHeight = ((float) max) / height;
float scaleWidth = ((float) max) / width;
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap and return it
return Bitmap.createBitmap(bmp, 0, 0, width, height, matrix, true);