Android自助餐之大图片加载
2016-07-11 19:26
337 查看
Android自助餐之大图片加载
原理
使用BitmapFactory.decodeStreeam()方法,该方法会调用native层代码来创建bitmap(两个重载都会调用)
使用带
BitmapFactory.Options参数的方法,改参数可指定生成bitmap的大小
思路
根据View尺寸或Window尺寸来确定bitmap的尺寸将确定好的尺寸放入
BitmapFactory.Options
调用
BitmapFactory.decodeStreeam()生成bitmap
步骤
根据图片路径或URI打开输入流InputStream is = getContentResolver().openInputStream(imageUri);
获取屏幕或View尺寸
如果能确定View尺寸则使用View尺寸,如果不能(比如动态调整的View、自适应的View等)则获取最接近该View的尺寸,实在不行就获取当前Activity的Window尺寸(比屏幕尺寸小)
获取Window尺寸
WindowManager windowManager = getWindowManager(); Display defaultDisplay = windowManager.getDefaultDisplay(); defaultDisplay.getHeight(); defaultDisplay.getWidth();
获取View尺寸
view.getMeasuredWidth(); view.getMeasuredHeight();
根据目标尺寸生成BitmapFactory.Options
BitmapFactory.Options option = new BitmapFactory.Options(); option.inSampleSize = dstSize;
使用options调用BitmapFactory.decodeStream()生成bitmap
Bitmap bitmap = BitmapFactory.decodeStream(is, null, option);
完整代码
InputStream is = null; try { int screenWidth=getWindowManager().getDefaultDisplay().getWidth(); int screenHeight=getWindowManager().getDefaultDisplay().getHeight(); int maxSize=Math.max(screenWidth,screenHeight);//以长边为准 is = getContentResolver().openInputStream(imageUri); BitmapFactory.Options option = new BitmapFactory.Options(); option.inSampleSize = maxSize; Bitmap bitmap = BitmapFactory.decodeStream(is, null, option); imageView.setImageBitmap(bitmap); } catch (Exception e) { e.printStackTrace(); } try{ if(is!=null)is.close(); }
相关文章推荐
- android动态添加删除控件以及设置宽高
- 用android-support-multidex解决Dex超出方法数的限制问题
- Android SO 加壳
- android中判断关于文本展示是否出现省略号的判断
- Android ImageLoader框架之图片缓存 (刚刚学习到,转载一篇)
- Android M新的运行权限
- Android 多线程
- Android中简单实现选择图片并裁剪
- AndroidException -Unable to add window -- token null is not valid;
- android平台短视频技术之 视频编辑的经验分享
- android EditText 禁止表情输入
- Android横竖屏切换总结
- android技术晋升之道
- Android利用canvas画各种图形(点、直线、弧、圆、椭圆、文字、矩形、多边形、曲线、圆角矩形)
- Android Studio 引用系统 jar 包的正确姿势
- mat工具使用
- Android倒计时工具类
- Android 主题换肤的开源库
- 原生Android系统的第一次开机google验证的解决
- 安卓学习-事件分发