Android ImageView大小不能与源图像缩放

我有一个LinearLayout内的几个ImageViews。 我需要缩小ImageViews,以便在垂直方向上适应LinearLayout的同时保持纵横比。 水平地,我只是需要他们彼此相邻。

我为此做了一个简化的testing平台,它嵌套了加权布局,以便为ImageView提供一个很宽但不是很高的LinearLayout,

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="5"> <LinearLayout android:id="@+id/linearLayout3" android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="1"> <ImageView android:id="@+id/imageView1" android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/test_image" android:scaleType="fitStart"></ImageView> <ImageView android:id="@+id/imageView2" android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/test_image" android:scaleType="fitStart"></ImageView> </LinearLayout> <LinearLayout android:id="@+id/linearLayout4" android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="1"></LinearLayout> </LinearLayout> <LinearLayout android:id="@+id/linearLayout2" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1"></LinearLayout> </LinearLayout> 

(在Eclipse布局编辑器中,图像垂直剪切,根本不缩放 – 但这只是我们学会爱的那些特质之一)

在硬件上运行时,图像缩放到正确的高度,同时保持其高宽比。 我的问题是,他们不是彼此相邻。 每个ImageView的高度正确匹配LinearLayout的高度。 每个ImageView的宽度是未缩放图像的宽度 – 实际缩小的图像出现在ImageViews的左侧。 正因为如此,我的图像之间差距很大。

理想情况下,我想通过XML进行pipe理,如果这不可能,我明白使用自定义视图可能是最好的解决scheme。

我试图创build一个IconView(扩展ImageView)类覆盖onMeasure,以便我可以通过根据高度缩放宽度创build必要的大小的图像视图。 但是传递给函数的parentWidth和parentHeight是屏幕的大小,而不是LinearLayout容器的大小。

 @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int parentWidth = MeasureSpec.getSize(widthMeasureSpec); int parentHeight = MeasureSpec.getSize(heightMeasureSpec); // Calculations followed by calls to setMeasuredDimension, setLayoutParams super.onMeasure(widthMeasureSpec, heightMeasureSpec); } 

所以我的问题是 –

1)我可以通过某种方式修改XML以使其符合我的需要吗?

2)我如何使我的自定义类获取LinearLayout的高度,以便我可以计算自定义图像的必要宽度?

谢谢,如果你已经设法阅读这一点。 如果你能指出我的解决scheme,更要感谢!

如何改变你的ImageViews使用android:layout_height="fill_parent"

编辑 – 花了我一会儿才发现,但看着源头帮我精确调整了adjustViewBounds 。 你可能想尝试添加android:adjustViewBounds="true"到你的ImageViews。 令人惊讶的是,这默认为false。

奇怪的android:layout_height="fill_parent"android:adjustViewBounds="true"没有帮助。 我遇到的问题是显示图像,但图像底部有块排,黑色排。 将缩放types设置为"centerCrop"帮助了我。 我想,原因是我的图像大小很小。

我有类似的问题,我的解决scheme是在XML布局文件中设置ImageView的android:scaleType="fitEnd"属性。