假设纵向模式,我有一个 ImageView,其图像大小可变(但始终为正方形)。我希望 ImageView 的宽度始终等于布局的宽度(fill_parent),并且您可以看到 scaleType 是“centerCrop”,它将进行缩放。
问题是,如果我将 *layout_height* 也设置为“fill_parent”,那么由于 centerCrop 保留了原始纵横比,因此高度优先并且图像在左右两侧被裁剪。(这当然假设屏幕比宽高)。但是,如果我将 layout_height 设置为“wrap_content”,则不再缩放高度,最终得到一个裁剪后的矩形。这样做是因为它尊重图像的原始高度。
是否有 layout_height 设置优先于“fill_parent”的 layout_width?
<ImageView
android:id="@+id/iv_image"
android:layout_width="fill_parent"
android:layout_height="?"
android:layout_below="@id/header"
android:layout_centerHorizontal="true"
android:contentDescription="@string/cd_image"
android:padding="0dp"
android:scaleType="centerCrop"
android:src="@drawable/blank_album" />
删除 android:layout_height 属性会导致崩溃:java.lang.RuntimeException:二进制 XML 文件第 16 行:您必须提供 layout_height 属性。
设置 android:layout_height="0dp" 垂直压碎图像。
答:结合其他用户的回答,我找到了一个适合我的简单解决方案。
首先,图像视图具有以下配置(注意fitStart):
<ImageView
android:id="@+id/iv_album"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@id/header"
android:layout_gravity="top"
android:background="#FF00FF00"
android:contentDescription="@string/app_name"
android:padding="0dp"
android:scaleType="fitStart"
android:src="@drawable/blank_album" />
然后以编程方式,对图像的高度进行小修改以匹配宽度(在 Activity.onResume() 内)
ImageView iv = (ImageView)findViewById(R.id.iv_album);
boolean bPost = iv.post(
new Runnable()
{
public void run()
{
ImageView iv = (ImageView)findViewById(R.id.iv_album);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)iv.getLayoutParams();
params.width = ASong.this.findViewById(R.id.song_view_layout_top).getWidth();
params.height = params.width;
iv.setLayoutParams(params);
}
});
if (bPost == false)
{
throw new RuntimeException("runnable not posted");
}