从Drawable.getIntrinsicWidth()得到的尺寸不正确。

3

我使用以下代码下载图片:

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;
    }
};

这张图片的尺寸是20x20。但是drawable.getIntrinsicWidth()和drawable.getIntrinsicHeight()返回27。并且图片看起来更大。我该如何解决?

2个回答

7

BitmapDrawable必须对位图进行缩放以适应不同的屏幕密度。

如果您需要按像素绘制,请尝试将Drawable的源密度和目标密度设置为相同的值。要做到这一点,您需要使用略有不同的对象。

而不是

drawable = Drawable.createFromPath(path);

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

如果您没有上下文(尽管您应该有),您可以使用应用程序上下文,例如参见在何处使用应用程序上下文?

由于位图的密度设置为资源的密度,即实际设备屏幕的密度,因此它应该可以不进行缩放绘制。


1
对于现在阅读此内容的任何人,API已更改,最后一行应为: drawable = new BitmapDrawable(context.getResources(), bmp); - Blue5hift

7

我尝试了答案中的代码,但没有成功。所以我使用了下面的代码,它可以很好地工作。

     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());

两个解决方案对我来说都可以用,但是您的更接近新的API变化。再次感谢。 - ForceMagic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接