Android如何最优化的读取一张Bitmap
来源:互联网 发布:淘宝服装货源 编辑:程序博客网 时间:2024/06/05 20:14
Drawable缓存问题,显示清晰度,
Resource.getDrawable会根据ID返回Drawable,然后把这个Drawable缓存起来,看以下这个代码段:
InputStream is = mAssets.openNonAsset( value.assetCookie, file, AssetManager.ACCESS_STREAMING); // System.out.println("Opened file " + file + ": " + is); dr = Drawable.createFromResourceStream(this, value, is, file, null); is.close();
dr.setChangingConfigurations(value.changingConfigurations); cs = dr.getConstantState(); if (cs != null) { if (mPreloading) { sPreloadedDrawables.put(key, cs); } else { synchronized (mTmpValue) { //Log.i(TAG, "Saving cached drawable @ #" + // Integer.toHexString(key.intValue()) // + " in " + this + ": " + cs); mDrawableCache.put(key, new WeakReference<Drawable.ConstantState>(cs)); } } }
缓存机制设计的很好,使用了弱引用机制避免内存溢出。但这个方法比较老实,如果资源是一张Bitmap的话,原图是多大,它就会生成多大的。为了让程序在不同的屏幕上面都比较清晰,并且图片占用内存不会过大,通常会根据不同的屏幕选择加载不同的图,但这样包大小又上去了,一般,我们会用到这样一个解决办法:
只放一张最大清晰度的图,程序运行时根据当前屏幕尺寸对图片进行缩放。
这个办法有一个缺点,就是加载时会先加载一张大图,再根据大图去生成小图,内存峰值是两张图,在内存紧张的手机上有什么办法么?下面是解决方案:
private BitmapDrawable getDrawable(int id) {int width = AppTools.getSreenSize(this, true);int height = AppTools.getSreenSize(this, false);BitmapFactory.Options opts = new BitmapFactory.Options();opts.inJustDecodeBounds = true;BitmapFactory.decodeResource(getResources(), id, opts);opts.inSampleSize = AppTools.computeSampleSize(opts, -1,(int) (width * height));opts.inJustDecodeBounds = false;Bitmap bitmap = null;try {bitmap = BitmapFactory.decodeResource(getResources(), id, opts);} catch (OutOfMemoryError e) {}if (bitmap == null) {return null;}return new BitmapDrawable(bitmap);}先使用获取图片的宽高,然后根据目标宽高计算出采样大小,最后再真正读取图片。
BitmapFactory.Options opts = new BitmapFactory.Options();opts.inJustDecodeBounds = true;BitmapFactory.decodeResource(getResources(), id, opts);
- Android如何最优化的读取一张Bitmap
- Android如何最优化的读取一张Bitmap
- Android 一张图片(BitMap)占用内存的计算 图片内存优化
- Android 一张图片(BitMap)占用内存的计算 图片内存优化
- Android 一张图片(BitMap)占用内存的计算 图片内存优化
- Android BitMap的优化
- Android Bitmap的优化
- Android的bitmap和优化
- Android的bitmap和优化
- Android的bitmap和优化
- Android的bitmap和优化
- Android的bitmap和优化
- Android的bitmap和优化
- Android:BitMap的性能优化
- Android的bitmap和优化
- Android的bitmap和优化
- android Bitmap拷贝一张图片
- 最简单的openCV语言,读取和显示一张图片
- linux:vi 替换命令
- Android设计应用图标不用愁---Asset Studio Integration来帮你
- 玩转UITableViewCell-1,可展开的单元格
- delphi SysErrorMessage 函数和系统错误信息表
- 为什么要学FI/CO
- Android如何最优化的读取一张Bitmap
- jquery提示[正在执行...]
- ubuntu源码编译安装php
- WinForm-Invalidate、Update、Refresh的区别
- wince中的xml解析
- ORACLE纯SQL实现多行合并一行【转】
- iOS 5 Storyboard: How To use Segues, Scenes and Static Content UITableViews--Part I
- 代理服务器 种类 功能
- GridView提示层以及ShowModalDialog使用方式备忘