Android显示从网络下载图片偏小的问题
16lz
2021-01-26
在从网络上下载图片时发现图片偏小,原来以为是BitmapFactory.decodeStream时BitmapFactory.Options的选择问题,但是试过了很多方法,达不到理想效果,后来发现是BitmapDrawable的使用问题,使用了BitmapDrawable(Bitmap bitmap)的构造方法,其实应该使用的是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;
更多相关文章
- Android:SQLite数据库
- android之图片截取
- Android(安卓)Activity生命周期以及Fragment生命周期的区别与分
- ArrayList动态删除 自定义Adapter (附源码)
- Android中JNI调用
- android 设置为壁纸代码
- Android(安卓)Gallery 的简单使用
- Android(安卓)RecyclerView 实现快速滑动
- Android:TextView显示富文本信息