在从网络上下载图片时发现图片偏小,原来以为是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;

更多相关文章

  1. Android:SQLite数据库
  2. android之图片截取
  3. Android(安卓)Activity生命周期以及Fragment生命周期的区别与分
  4. ArrayList动态删除 自定义Adapter (附源码)
  5. Android中JNI调用
  6. android 设置为壁纸代码
  7. Android(安卓)Gallery 的简单使用
  8. Android(安卓)RecyclerView 实现快速滑动
  9. Android:TextView显示富文本信息

随机推荐

  1. BuildGradle自定义打包
  2. Mac OS下Android开发环境配置详解
  3. android 自定义封装android 6.0以上动态
  4. 如何把win32下写好的cocos2d-x 转到andro
  5. Android启动Activity中间黑屏
  6. appium自动化测试Android Demo
  7. 圆形ImageView
  8. Android多媒体开发【5】-- Stagefright原
  9. 两种方式实现Android侧滑菜单
  10. Android进行全屏设置