【问题标题】:How to get width and height of the image?如何获取图像的宽度和高度?
【发布时间】:2011-05-31 23:17:36
【问题描述】:

你好,

我想获取存储在可绘制文件夹中的图像的宽度和高度。 这可能吗,如果可以,请告诉我?

【问题讨论】:

标签: android


【解决方案1】:

试试

BitmapDrawable bd=(BitmapDrawable) this.getResources().getDrawable(R.drawable.icon);
int height=bd.getBitmap().getHeight();
int width=bd.getBitmap().getWidth();

【讨论】:

  • 我宁愿不用强制转换,使用 Drawable.getIntrinsicWidth/Height()。
  • 使用上面的代码,得到原始大小的三分之二。例如,图像的尺寸为 644 X 550;但我从代码中得到 429 X 367。可能是什么问题?
  • 您有多个密度文件夹吗? hdpi和mdpi?听起来 BitmapDrawable 对选择哪个感到困惑。在选项中设置正确的密度,如developer.android.com/reference/android/graphics/…
  • getDrawable 方法已弃用。使用哪种方法代替“getDrawable”方法
  • getDrawable 的非弃用版本是 ResourcesCompat.getDrawable,它支持主题。如果您不需要主题,只需将 null 传递给它(此处的文档:developer.android.com/reference/android/support/v4/content/res/…)。
【解决方案2】:

我已经关注this 链接:-

Drawable d = getResources().getDrawable(R.drawable.yourimage);
int h = d.getIntrinsicHeight();
int w = d.getIntrinsicWidth();

【讨论】:

  • 这对我更适用,因为它为您提供了与天气无关的视图大小,它是否显示在屏幕上!