imageView.getWidth();返回屏幕而不是位图宽度

时间:2013-02-25 14:38:43

标签: android android-layout android-imageview

我有一个看起来像这样的图像视图

 <ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_alignTop="@+id/textView3"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="80dp"
    android:layout_marginTop="40dp"
    android:onClick="Time"
    android:adjustViewBounds="false"
    android:src="@drawable/ic_launcher" />

我正在尝试使用

获取图像视图中显示的图像宽度
ImageView artCover = (ImageView)findViewById(R.id.imageView1);
int coverWidth = artCover.getWidth();

但返回的宽度与屏幕宽度相同而不是图像(当图像宽度小于屏幕宽度时)。如果我做

int coverHeight = artCover.getHeight(); 

我得到正确的图像高度。如何获得显示图像的宽度?

3 个答案:

答案 0 :(得分:8)

您的imageview的位图可能会相应缩放和对齐。你需要考虑到这一点。

// Get rectangle of the bitmap (drawable) drawn in the imageView.
RectF bitmapRect = new RectF();
bitmapRect.right = imageView.getDrawable().getIntrinsicWidth();
bitmapRect.bottom = imageView.getDrawable().getIntrinsicHeight();

// Translate and scale the bitmapRect according to the imageview's scale-type, etc. 
Matrix m = imageView.getImageMatrix();
m.mapRect(bitmapRect);

// Get the width of the image as shown on the screen:
int width = bitmapRect.width();

(请注意,我没有尝试编译上面的代码,但你会得到它的要点:-))。 上述代码仅在ImageView完成其布局时才有效。

答案 1 :(得分:1)

您必须等到完全测量View树,这可能比onPostResume()更晚。解决这个问题的一种方法是:

final ImageView artCover = (ImageView)findViewById(R.id.imageView1);
artCover.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
        public void onGlobalLayout() {
            int coverWidth = artCover.getWidth();
        }
    }
);

答案 2 :(得分:1)

您可以从imageview获取图像并获得图像的宽度。

Bitmap bitmap = ((BitmapDrawable)artCover.getDrawable()).getBitmap();<p>
bitmap.getWidth();
相关问题