带有自定义可绘制缩放比例的内容插入

Content Inset with Custom Drawable Scaling

我有一个 ListView,其中包含在 relativeLayout 中定义的自定义项目,其中包括一个带有 android:layout_width="match_parent"android:layout_height="wrap_content" 的 imageView 以及一个作为源的自定义矢量可绘制对象,其示意图如下所示:

+-------------------------------------------+
+    solid area              | some picture +
+-------------------------------------------+

问题是当我转到横向模式时,图像会按比例放大(以匹配父级的宽度),但是保持纵横比也会增加高度。

理想情况下,我想定义一个 Content Inset(我从 iOS 知道的),这样上面的实心区域就会被拉伸以匹配新的宽度,而 'some picture' 区域保持相同的纵横比。总而言之,我会进行缩放,使图像的高度(以及整个 listView 项目的高度)保持不变。

您可以使用 LinearLayout 和子宽度中的 weight 布局来拉伸实心区域。为了使这项工作有效,您应该为 ImageView.

分配固定宽度

此外,ImageView 上的 adjustViewBounds 属性将有助于保持正确的纵横比。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:orientation="horizontal">

    <!-- this can be any view or view group, the layout params are the important part-->
    <View
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        ...
        />

    <!-- set this to an absolute width that will be the same for portrait & landscape -->
    <ImageView
        android:layout_width="240dp"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        ...
        />

</LinearLayout>