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

aze*_*eam 1 android android-layout android-imageview

我有一个看起来像这样的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" />
Run Code Online (Sandbox Code Playgroud)

我试图通过使用获得图像视图中显示的图像的宽度

ImageView artCover = (ImageView)findViewById(R.id.imageView1);
int coverWidth = artCover.getWidth();
Run Code Online (Sandbox Code Playgroud)

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

int coverHeight = artCover.getHeight(); 
Run Code Online (Sandbox Code Playgroud)

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

Str*_*ton 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();
Run Code Online (Sandbox Code Playgroud)

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