如果在xml中设置了两个维度,则其行为符合预期,例如
android:layout_width="250dp"
android:layout_height="250dp"
如果留给wrap_content,则不会。
这是我的布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/board"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="@drawable/board" />
</LinearLayout>
为什么我在屏幕上看到的图像具有正确的尺寸(屏幕高度x屏幕高度,因为它是方形位图,我为高度设置match_parent),但是如果我调用ImageView.getWidth()和ImageView.getHeight()它给我屏幕尺寸?
祝你好运
答案 0 :(得分:5)
这种情况正在发生,因为我在此处提供了您之前提出的问题 https://stackoverflow.com/a/10183799/1244489
当你调用getWidth()和getHeight()时,它会返回你的ImageView的大小,如果你观察到它是全屏大小。您的源图像已缩小以适应保持其宽高比的屏幕,但ImageView不会缩小。要将其缩小到图像大小,您需要提供参数
在你的ImageView中机器人:adjustViewBounds = “真”
。
答案 1 :(得分:1)
在这里找到答案: Fit image into ImageView, keep aspect ratio and then resize ImageView to image dimensions?
这是问题的根源:ImageView没有根据图像尺寸调整尺寸,因此我们必须自己调整尺寸:
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) imageView.getLayoutParams();
params.width = width;
params.height = height;
imageView.setLayoutParams(params);
答案 2 :(得分:0)
因为getWidth()
和getHeight()
是从View
层次结构中调用的,因为它们是屏幕尺寸。实际上,如果使用ImageView'
的缩放类型(如fitCenter)缩放图像,则所获得的尺寸将与图像完全不匹配。它们将保留整个视图的像素宽度和像素高度,而不仅仅是图像占用的像素宽度和像素高度。