我正在写一个音乐应用程序,我已经获得了专辑艺术。然而,它们出现了各种尺寸。那么,我如何标准化返回的位图的大小?
答案 0 :(得分:4)
你会做这样的事情:
// load the origial BitMap (500 x 500 px)
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.android);
int width = bitmapOrg.width();
int height = bitmapOrg.height();
int newWidth = 200;
int newHeight = 200;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
width, height, matrix, true);
答案 1 :(得分:0)
或者,当您在画布上绘制位图时,可以将位图缩放到所需的大小:
来自android文档:
drawBitmap(位图位图,Rect src,Rect dst,Paint paint) 绘制指定的位图,自动缩放/平移以填充目标矩形。
使src为null,dst是一个Rect,你想要它在画布上的大小/位置,设置如
Rect rect = new Rect(0, 0, width, height)
canvas.drawBitmap(bitmap, null, rect)
答案 2 :(得分:0)
根据我的经验,接受的答案中的代码不起作用,至少在某些平台上是这样。
Bitmap.createBitmap(bitmapOrg, 0, 0, width, height, matrix, true);
会以原始尺寸为您提供缩减采样图像 - 所以只是模糊的图像。
有趣的是,代码
Bitmap resizedBitmap = Bitmap.createScaledBitmap(square, (int) targetWidth, (int) targetHeight, false);
也会产生模糊的图像。在我的情况下,有必要这样做:
// RESIZE THE BIT MAP
// According to a variety of resources, this function should give us pixels from the dp of the screen
// From http://stackoverflow.com/questions/4605527/converting-pixels-to-dp-in-android
float targetHeight = DWUtilities.convertDpToPixel(80, getActivity());
float targetWidth = DWUtilities.convertDpToPixel(80, getActivity());
// However, the above pixel dimension are still too small to show in my 80dp image view
// On the Nexus 4, a factor of 4 seems to get us up to the right size
// No idea why.
targetHeight *= 4;
targetWidth *= 4;
matrix.postScale( (float) targetHeight / square.getWidth(), (float) targetWidth / square.getHeight());
Bitmap resizedBitmap = Bitmap.createBitmap(square, 0, 0, square.getWidth(), square.getHeight(), matrix, false);
// By the way, the below code also gives a full size, but blurry image
// Bitmap resizedBitmap = Bitmap.createScaledBitmap(square, (int) targetWidth, (int) targetHeight, false
我还没有进一步的解决方案,但希望这对某人有帮助。