Android显示从网络下载图片偏小的问题
2016-01-12 14:57
691 查看
在从网络上下载图片时发现图片偏小,原来以为是BitmapFactory.decodeStream时BitmapFactory.Options的选择问题,但是试过了很多方法,达不到理想效果,后来发现是BitmapDrawable的使用问题,使用了BitmapDrawable(Bitmap bitmap)的构造方法,其实应该使用的是BitmapDrawable(Resources res, Bitmap bitmap),看注释应该明白:
BitmapDrawable(Bitmap bitmap)本身是个Deprecated的方法,它没有制定resources,就不知道屏幕的分辨率,那么mTargetDensity就用默认值DisplayMetrics.DENSITY_DEFAULT = 160,就会导致图片解码不合适。
用BitmapDrawable(Resources res, Bitmap bitmap)就可以了。
下面附上网络下载图片的两种方法:
/** * Create drawable from a bitmap, setting initial target density based on * the display metrics of the resources. */
BitmapDrawable(Bitmap bitmap)本身是个Deprecated的方法,它没有制定resources,就不知道屏幕的分辨率,那么mTargetDensity就用默认值DisplayMetrics.DENSITY_DEFAULT = 160,就会导致图片解码不合适。
用BitmapDrawable(Resources res, Bitmap bitmap)就可以了。
下面附上网络下载图片的两种方法:
try { String url = params[0]; InputStream inputStream = new URL(url).openStream(); BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); decodeOptions.inPreferredConfig = Bitmap.Config.ARGB_8888; decodeOptions.inDensity = 0; Bitmap bitmap = BitmapFactory.decodeStream(inputStream,null, decodeOptions); return new BitmapDrawable(getResources(), bitmap); } catch (Exception e) { e.printStackTrace(); } return null;
try { URL url = new URL(params[0]); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5 * 1000); conn.setRequestMethod("GET"); if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){ InputStream inStream = conn.getInputStream(); BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); decodeOptions.inPreferredConfig = Bitmap.Config.ARGB_8888; decodeOptions.inDensity = 0; Bitmap bitmap = BitmapFactory.decodeStream(inStream,null, decodeOptions); return new BitmapDrawable(getResources(), bitmap); } } catch (Exception e) { e.printStackTrace(); } return null;
相关文章推荐
- HTTP的请求头标签 If-Modified-Since
- android之HttpURLConnection
- 09_android入门_採用android-async-http开源项目的GET方式或POST方式实现登陆案例
- Ubuntu打开右上脚网络小图标
- No http handler was found for request type 'GET'
- iOS网络请求NSURLSession
- iOS网络请求NSURLConnection
- ASI简单实现网络编程
- Comet:基于 HTTP 长连接的“服务器推”技术
- 基于TCP的RTP协议传输
- httpclient调用工具类
- ipython notebook http://localhost:8888/tree error
- 未来数据中心网络的三大武器: SDN、Overlay、VDC
- 灵活定义神经网络结构
- HTTP请求模型和头信息
- HTTP 头部解释
- IOS使用Reachability实时检测网络连接状况
- IOS-利用AFNetworking监听网络状态
- linux下出现ping:unknown host www.baidu.com问题时的解决办法——ubuntu下局域网络的配置
- 坑爹的 HTTPClient java.lang.NoSuchFieldError: INSTANCE