Android显示从网络下载图片偏小的问题

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