2012-10-22 49 views
3

我下载的图像与此代码:大小从Drawable.getIntrinsicWidth错误的()

ImageGetter imageGetter = new ImageGetter() { 
    @Override 
    public Drawable getDrawable(String source) { 
     Drawable drawable = null; 
     try { 
      URL url = new URL(source); 
      String path = Environment.getExternalStorageDirectory().getPath()+"/Android/data/com.my.pkg/"+url.getFile(); 
      File f=new File(path); 
      if(!f.exists()) { 
       URLConnection connection = url.openConnection(); 
       InputStream is = connection.getInputStream(); 

       f=new File(f.getParent()); 
       f.mkdirs();     

       FileOutputStream os = new FileOutputStream(path); 
       byte[] buffer = new byte[4096]; 
       int length; 
       while ((length = is.read(buffer)) > 0) { 
        os.write(buffer, 0, length); 
       } 
       os.close(); 
       is.close(); 
      } 
      drawable = Drawable.createFromPath(path); 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (Throwable t) { 
      t.printStackTrace(); 
     } 
     if(drawable != null) { 
      drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); 
     } 
     return drawable; 
    } 
}; 

此图片的大小为20×20。但drawable.getIntrinsicWidth()和drawable.getIntrinsicHeight()的返回27和图像看起来更大。我如何解决它?

回答

5

BitmapDrawable必须扩展位,以补偿不同的屏幕密度。

如果你需要它来绘制的像素对像素,尝试绘制对象的源密度&目标密度设置为相同的值。要做到这一点,你需要稍微不同的对象来处理。

而不是

drawable = Drawable.createFromPath(path); 

使用

Bitmap bmp = BitmapFactory.decodeFile(path); 
DisplayMetrics dm = context.getResources().getDisplayMetrics(); 
bmp.setDensity(dm.densityDpi); 
drawable = new BitmapDrawable(bmp, context.getResources()); 

如果没有上下文(你应该),你可以使用应用程序上下文,例如见Using Application context everywhere?

由于位图的密度设置为资源的密度,这是实际的设备屏幕的密度,这应该引起不结垢。

6

我试过代码形式的答案,没有工作。所以,而是我使用下面的代码,它工作正常。

 DisplayMetrics dm = context.getResources().getDisplayMetrics(); 

    Options options=new Options(); 
    options.inDensity=dm.densityDpi; 
    options.inScreenDensity=dm.densityDpi; 
    options.inTargetDensity=dm.densityDpi;  

    Bitmap bmp = BitmapFactory.decodeFile(path,options); 
    drawable = new BitmapDrawable(bmp, context.getResources()); 
+0

这两种解决方案都适用于我,但是,您更接近于新的API更改。再次感谢。 – ForceMagic