android - Drawable.getIntrinsicWidth() 的尺寸错误

标签 android image

我用这段代码下载图片:

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。图像看起来更大。我该如何解决?

最佳答案

我尝试了答案中的代码,但没有成功。所以我改用下面的代码,它运行良好。

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

关于android - Drawable.getIntrinsicWidth() 的尺寸错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13013986/

相关文章:

javascript - 如何获取图像的高度?

java - 在 android 中调整图片大小同时仍保持质量

java - Jsoup不解析表中的数据

Android Studio Designer 找不到类

java - 如何在较新版本的 Android 3.1 及更高版本中实现 Firebase Recycler Adapter?

html - 无法通过 <img> 标签显示图片

javascript - JS 图片预加载被阻止?

c# - 如何在虚拟模式下在所有 ListView 项上显示图标 (C#)

android - Nexus S 未显示在 DDMS 上

java - android-为什么我无法获取设备方向?