有效地加载大尺寸位图(Loading Large Bitmaps Efficiently)

有效地加载大尺寸位图(LoadingLargeBitmapsEfficiently)

图片有不同的形状与大小。在大多数情况下它们的实际大小都比需要呈现出来的要大很多。例如,系统的

考虑到程序是在有限的内存下工作,理想情况是你只需要在内存中加载一个低分辨率的版本即可。这个低分辨率的版本应该是与你的

这一课会介绍如何通过加载一个缩小版本的图片到内存中去

读取位图的尺寸与类型(ReadBitmapDimensionsandType)

BitmapFactory

BitmapFactory.Optionsoptions=newBitmapFactory.Options();

options.inJustDecodeBounds=true;

BitmapFactory.decodeResource(getResources(),R.id.myimage,options);

intimageWidth=options.outWidth;

StringimageType=options.outMimeType;

为了避免

加载一个按比例缩小的版本到内存中(LoadaScaledDownVersionintoMemory)

通过上面的步骤我们已经知道了图片的尺寸,那些数据可以用来决定是应该加载整个图片到内存中还是加载一个缩小的版本。有下面一些因素需要考虑:

评估加载完整图片所需要耗费的内存。

程序在加载这张图片时会涉及到其他内存需求。

呈现这张图片的组件的尺寸大小。

屏幕大小与当前设备的屏幕密度。

例如,如果把一个原图是

为了告诉

publicstaticintcalculateInSampleSize(

BitmapFactory.Optionsoptions,intreqWidth,intreqHeight){

//Rawheightandwidthofimage

finalintheight=options.outHeight;

finalintwidth=options.outWidth;

intinSampleSize=1;

if(height>reqHeight||width>reqWidth){

finalinthalfHeight=height/2;

finalinthalfWidth=width/2;

//CalculatethelargestinSampleSizevaluethatisapowerof2andkeepsboth

//heightandwidthlargerthantherequestedheightandwidth.

while((halfHeight/inSampleSize)>reqHeight

&&(halfWidth/inSampleSize)>reqWidth){

inSampleSize*=2;

}

}

returninSampleSize;

}

Note:

为了使用这个方法,首先需要设置

publicstaticBitmapdecodeSampledBitmapFromResource(Resourcesres,intresId,

intreqWidth,intreqHeight){

//FirstdecodewithinJustDecodeBounds=truetocheckdimensions

finalBitmapFactory.Optionsoptions=newBitmapFactory.Options();

options.inJustDecodeBounds=true;

BitmapFactory.decodeResource(res,resId,options);

//CalculateinSampleSize

options.inSampleSize=calculateInSampleSize(options,reqWidth,reqHeight);

//DecodebitmapwithinSampleSizeset

options.inJustDecodeBounds=false;

returnBitmapFactory.decodeResource(res,resId,options);

}

使用上面这个方法可以简单的加载一个任意大小的图片并显示为

mImageView.setImageBitmap(

decodeSampledBitmapFromResource(getResources(),R.id.myimage,100,100));

你可以通过替换合适的

,莫找借口失败,只找理由成功。

有效地加载大尺寸位图(Loading Large Bitmaps Efficiently)

相关文章:

你感兴趣的文章:

标签云: