1

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

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

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

4

3 回答 3

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 完成布局后才有效。

于 2013-02-25T15:56:07.607 回答
1

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

Bitmap bitmap = ((BitmapDrawable)artCover.getDrawable()).getBitmap();<p>
bitmap.getWidth();
于 2013-02-25T15:04:52.210 回答
1

您必须等到完全测量完视图树,这可能比 onPostResume() 还要晚。一种处理方法是:

final ImageView artCover = (ImageView)findViewById(R.id.imageView1);
artCover.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
        public void onGlobalLayout() {
            int coverWidth = artCover.getWidth();
        }
    }
);
于 2013-02-25T14:47:45.050 回答