Android优化之bitmap图片
来源:互联网 发布:单片机仿真需要程序吗 编辑:程序博客网 时间:2024/05/19 17:24
在android项目的imageview中使用大图bitmap时会占据很大的内存,而且在很多时候我们并不需要显示原图那么大的图片,比如一个100*100的图片,我们只需要显示50*50,直接设置的话会造成大量的内存浪费。
所以我们需要对图片进行优化,减少内存开销。我们会使用BitmapFactory.Options的方法来进行图片缩放,先介绍几个重要的属性。
inJustDecodeBounds:这个属性当设置为true时,在bitmapfactory创建bitmap对象时,我们仍然可以获取到bitmap的属性,但是不会分配内存,这时我们就能对其操作进行缩小或者放大。
inSampleSize:设置图片缩放的比例,比如设为2时,长宽各缩放两倍,然后整个图片缩小了4倍。
private Bitmap swapBitmap(float imagew ,float imageh ,int id){ BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; //先设置为true再decode图片资源,节省内存 bitmap = BitmapFactory.decodeResource(getResources(), id, options); int yRadio = (int) Math.ceil(options.outHeight / imageh); int xRadio = (int) Math.ceil(options.outWidth / imagew); if (yRadio > 1 || xRadio >1) {if (yRadio > xRadio) {options.inSampleSize = yRadio;}else {options.inSampleSize = xRadio;}}else {Toast.makeText(this, "insimplesize的值 : 1" ,Toast.LENGTH_SHORT).show();} options.inJustDecodeBounds = false; bitmap = BitmapFactory.decodeResource(getResources(),id, options); return bitmap; }这个方法参数为预计缩放的宽,高,以及图片资源的id,宽高是px格式的。
调用如下:
Bitmap bitmap2 = swapBitmap(50, 50,R.drawable.ic_launcher); view.setImageBitmap(bitmap2);另外因为我们在上面设置的是px,在不同分辨率的手机上会显示出差异,所以需要将预先设置的dp转为px.
//dp convert to px private int dp2px(float dipValue){ float scale = getResources().getDisplayMetrics().density; Log.i("scale", String.valueOf(scale)); return (int) (dipValue*scale+0.5f); } //px convert to dp private int px2dp(float pxValue){ float scale = getResources().getDisplayMetrics().density; Log.i("scale", String.valueOf(scale)); return (int) (pxValue / scale +0.5f); }
0 0
- Android优化之bitmap图片
- Android性能优化系列之Bitmap图片优化
- Android性能优化系列之Bitmap图片优化
- Android性能优化系列之Bitmap图片优化
- Android 图片压缩,Bitmap优化
- Android Bitmap 优化- 图片压缩
- Android Bitmap 优化- 图片压缩
- Android Bitmap 优化- 图片压缩
- Android内存优化之Bitmap
- Android图片之bitmap缩略图
- Android图片之Bitmap、BitmapFactory
- android之bitmap处理图片
- Android Bitmap 优化(2) - 图片缓存
- Android性能优化之:加载Bitmap优化
- android优化(二)---App调试内存泄露之图片Bitmap篇
- android优化(二)---App调试内存泄露之图片Bitmap篇
- 安卓图片优化之Bitmap优化(一)
- 优化Bitmap图片
- JAVA中的各种路径问题
- NGX打印日志时对特殊字符的转码
- ios调打电话代码
- OCP-1Z0-051-2015-28题
- 短小精干,大道至简-----Sikuli截图尝试
- Android优化之bitmap图片
- Java abstract class vs interface
- UI控件
- [win7系统]telnet服务
- linux知识点回顾
- 图片上传,android ios Java服务器整合
- c++ primer读书笔记-第六章 语句
- iOS并发编程指南
- hmac-sha1加密算法C源码示例