46

在 ImageView 中检索 Drawable 尺寸的最佳方法是什么?

ImageView有一个初始化方法,我在其中创建ImageView

private void init() {
    coverImg = new ImageView(context);
    coverImg.setScaleType(ScaleType.FIT_START);
    coverImg.setImageDrawable(getResources().getDrawable(R.drawable.store_blind_cover));
    addView(coverImg);
}

在布局或测量过程中的某个时刻,我需要 Drawable 的确切尺寸来调整它周围的其余组件。

coverImg.getHeight()并且coverImg.getMeasuredHeight()不要返回我需要的结果,如果我使用coverImg.getDrawable().getBounds()我会在它被缩放之前得到尺寸ImageView

谢谢你的帮助!

4

5 回答 5

53

刚刚尝试了一下,它对我有用:

int finalHeight, finalWidth;
final ImageView iv = (ImageView)findViewById(R.id.scaled_image);
final TextView tv = (TextView)findViewById(R.id.size_label);
ViewTreeObserver vto = iv.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    public boolean onPreDraw() {
        // Remove after the first run so it doesn't fire forever
        iv.getViewTreeObserver().removeOnPreDrawListener(this);
        finalHeight = iv.getMeasuredHeight();
        finalWidth = iv.getMeasuredWidth();
        tv.setText("Height: " + finalHeight + " Width: " + finalWidth);
        return true;
    }
});

ViewTreeObserver将让您在绘制布局之前监控布局(即所有内容都已测量),从这里您可以从ImageView.

于 2011-01-10T17:58:22.593 回答
46

在可绘制对象上调用 getIntrinsicHeight 和 getIntrinsicWidth。

public int getIntrinsicHeight ()

自:API 级别 1

返回底层可绘制对象的固有高度。如果它没有固有高度,例如纯色,则返回 -1。

public int getIntrinsicWidth ()

自:API 级别 1

返回底层可绘制对象的固有宽度。

如果它没有固有宽度,例如纯色,则返回 -1。

http://developer.android.com/reference/android/graphics/drawable/Drawable.html#getIntrinsicHeight()

这是原始可绘制对象的大小。我想这就是你想要的。

于 2011-01-13T14:28:26.163 回答
24

对我来说,获得可绘制尺寸的最可靠和最强大的方法是使用 BitmapFactory 来解码位图。它非常灵活——它可以解码来自可绘制资源、文件或其他不同来源的图像。

以下是使用 BitmapFactory 从可绘制资源中获取尺寸的方法:

BitmapFactory.Options o = new BitmapFactory.Options();
o.inTargetDensity = DisplayMetrics.DENSITY_DEFAULT;
Bitmap bmp = BitmapFactory.decodeResource(activity.getResources(),
                                               R.drawable.sample_image, o);
int w = bmp.getWidth();
int h = bmp.getHeight();

如果在 res 下使用多个密度可绘制文件夹,请务必小心,并确保在 BitmapFactory.Options 上指定 inTargetDensity 以获得所需密度的可绘制对象。

于 2012-01-18T20:52:50.913 回答
13

获取Drawable宽度高度的有效方法:

Drawable drawable = getResources().getDrawable(R.drawable.ic_home);
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
Log.i("Drawable dimension : W-H", width+"-"+height);

希望这会帮助你。

于 2016-02-09T12:48:35.020 回答
6

这解决了我的问题。它在不真正加载整个图像的情况下解码图像边界的大小。

BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.img , o);
int w = o.outWidth;
int h = o.outHeight;
于 2014-11-24T00:36:03.363 回答