标签:系统 空手套白狼 als 手机 string and ref uitable static
一方面是由于图像处理不好的话会很占内存,并且easyOOM,还有一方面,图像也比文字要大,载入比較慢。所以,在解说了怎样进行多线程、AsyncTask进行多线程载入后,先暂停下后面的学习。来对图像的异步处理进行一些优化工作。
相同一张图片。假设放在4.7寸的手机上,当然,相同还是一张高清无码大图,但这张图片10M,在电脑上可能不算什么,但在手机上,已经是很大了,而这张图片在手机上,你拼命看。也就是那样,即使分辨率降低一半。你看上去也还是差点儿相同。
这就像所谓的视网膜屏、2k屏、4k屏,事实上已经基本达到视觉分析的极限了。一般情况下,区别并不大。
所以。我们在下载高分辨率的图片的时候。能够对图像进行压缩,显示上尽管没有太大区别,可是却帮系统节省了大量的私房钱。
这时候,Options參数中的图像宽高、类型等属性已经被赋值了,这样。我们就实现了空手套白狼,哦,不正确,是不使用内存就获取图像的属性。
BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(getResources(), R.id.myimage, options); // 获取属性值 int imageHeight = options.outHeight; int imageWidth = options.outWidth; String imageType = options.outMimeType;
OK,以下我们就通过这样一个方法来对图像进行优化,首先,我们须要创建一个方法来获取到一个合适的inSampleSize:
/**
* 获取合适的inSampleSize
* @param options
* @param targetWidth 期望Width
* @param targetHeight 期望Height
* @return
*/
public static int getInSampleSize(BitmapFactory.Options options,
int targetWidth, int targetHeight) {
// 原始图片的高度和宽度
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > targetHeight || width > targetWidth) {
// 计算出实际宽高和目标宽高的比率
final int heightRate = Math.round((float) height / (float) targetHeight);
final int widthRate = Math.round((float) width / (float) targetWidth);
inSampleSize = heightRate < widthRate ? heightRate : widthRate;
}
return inSampleSize;
}
/**
* 使用targetWidth、targetHeight来获取合适的inSampleSize
* 并使用inSampleSize来缩放得到合适大小的图像
* @param res getResources()
* @param resId id
* @param targetWidth
* @param targetHeight
* @return
*/
public static Bitmap decodeSuitableBitmap(Resources res, int resId,
int targetWidth, int targetHeight) {
// 空手套白狼
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// 计算合适的inSampleSize
options.inSampleSize = getInSampleSize(options, targetWidth, targetHeight);
// 载入到内存
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}标签:系统 空手套白狼 als 手机 string and ref uitable static
原文地址:http://www.cnblogs.com/cxchanpin/p/6786247.html