大佬教程收集整理的这篇文章主要介绍了android – 在设备上创建位图时内存不足,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用Nodpi-drawable文件夹为1280×720图像,并使用此代码来缩放它.
public static Drawable scaleDrawable(Drawable d,int width,Activity cxt) { BitmapDrawable bd = (BitmapDrawablE)d; double oldWidth = bd.getBitmap().getWidth(); double scaleFactor = width / oldWidth; int newHeight = (int) (d.geTintrinsicHeight() * scaleFactor); int newWidth = (int) (oldWidth * scaleFactor); Drawable drawable = new BitmapDrawable(cxt.getresources(),MainScreen.getResizedBitmap(bd.getBitmap(),newHeight,newWidth)); BitmapDrawable bd2 = (BitmapDrawablE)drawable; return drawable; } public static Bitmap getResizedBitmap(Bitmap bm,int newHeight,int newWidth) { int width = bm.getWidth(); int height = bm.getHeight(); float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; // create a matrix for the manipulation Matrix matrix = new Matrix(); // resize the bit map matrix.postScale(scaleWidth,scaleHeight); // recreate the new Bitmap Bitmap resizedBitmap = Bitmap.createBitmap(bm,width,height,matrix,falsE); return resizedBitmap; }
我使用该代码将图像缩放到屏幕,所以如果屏幕是320×480,图像将缩放到320并保持比例,我不在乎图像是否从底部离开屏幕.
所有它的工作正常,但尝试在xhdpi设备特别是三星Galaxy Note 2与屏幕正好720×1280.
它在行中出现Out of Memory Exception崩溃:
Bitmap resizedBitmap = Bitmap.createBitmap(bm,falsE);
我不明白为什么,图像应该从720到720,但我的代码必须是非常糟糕的优化或其他东西.
我没有试过1080×1920设备,但它似乎也会崩溃.
在查看代码时,有人会看到一些不好的东西吗?
Bitmap bm=decodeSampledBitmapFromPath(src,reqWidth,reqHeight);
使用这个定义 –
public Bitmap decodeSampledBitmapFromPath(String path,int reqWidth,int reqHeight) { final BitmapFactory.options options = new BitmapFactory.options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path,options); options.inSampleSize = calculateInSampleSize(options,reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; Bitmap bmp = BitmapFactory.decodeFile(path,options); return bmp; } } public int calculateInSampleSize(BitmapFactory.options options,int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { if (width > height) { inSampleSize = Math.round((float) height / (float) reqHeight); } else { inSampleSize = Math.round((float) width / (float) reqWidth); } } return inSampleSize; }
如果您正在使用资源,则使用BitmapFactory的decoderesource方法替换方法.
public static Bitmap decodeSampledBitmapFromresource(resources res,int resId,int reqHeight) { .... ..... return BitmapFactory.decoderesource(res,resId,options); }
以上是大佬教程为你收集整理的android – 在设备上创建位图时内存不足全部内容,希望文章能够帮你解决android – 在设备上创建位图时内存不足所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。