在Android中按比例调整ImageView的大小

3
假设您有以下内容:
<ImageView
        android:id="@+id/mainImageView"
        android:layout_width="match_parent"
        android:background="@drawable/mylogo_250px60px"
/>

我希望定义高度,以便它可以根据宽度进行比例缩放。因此,如果Android决定按宽度缩放标志,高度也应相应增加。

当手机从垂直状态变为水平状态时,是否也可以定义某些内容,使标志正确缩放?

(基本上,标志位于主活动的列表视图上方)

我也尝试过使用这个方法,但没有成功(与宽度相比,高度显得太低。图像未在高度上调整大小/缩放)

<ImageView
        android:id="@+id/mainImageView"
        android:layout_width="match_parent"
        android:background="@drawable/mylogo_250px60px"
        android:layout_height="wrap_content"
        android:scaleType="centerInside"
        android:adjustViewBounds="true"                                       
    />

如果我在Eclipse/ADT GUI工具中设计它,标志将获得76dp,并且在我的两部测试手机上看起来很好。但是,我认为应该可以简单地按比例缩放图像?“固定高度”在宽度方面有正确的比率(垂直视图,而不是手机倾斜时),“自动高度”相比宽度比例似乎出现了问题。

1
请问您能否向我们展示一下输出图像? - Sankar V
好的。我会上传76dp高度版本+建议的更改,但似乎没有生效。 - Tom
我现在已经上传了两张截图。我想我可以使用固定大小,但我更喜欢使用自动调整大小和比例的配置,无论什么情况下都能正确缩放图片。 - Tom
请展示我们期望输出的图像。 - Sankar V
那是截图编号1。那就是我想要的样子。(真实/正确的比例)我只能通过使用固定的dp高度来实现这一点,但这是有问题的,例如当手机倾斜到水平视图时。 - Tom
3个回答

11

将您的ImageView代码更改如下:

 <ImageView
        android:id="@+id/mainImageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/mylogo_250px60px"
        android:scaleType="fitEnd"
        android:adjustViewBounds="true"
    />

1
不幸的是,高度继续保持小的状态(未调整大小/缩放),而宽度被拉伸以匹配父容器的宽度。 - Tom
如果您的图像可以制作9-patch可绘制对象,则可以尝试使用它。 - Sankar V

1

试试这个:

<ImageView
        android:id="@+id/mainImageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/mylogo_250px60px"
        android:scaleType="fitEnd"
        android:adjustViewBounds="true"
        />

希望它有所帮助。

需要使用9 patch图像时,Android:adjustViewBounds是必需的。谢谢。 - francas

-1

这个很好用:

<ImageView
    android:id="@+id/mainImageView"
    android:layout_width="wrap_content"
    android:background="@drawable/mylogo_250px60px"
    android:layout_height="wrap_content"                                      
/>

唯一的问题:可绘制对象必须至少与其父级一样宽。
渲染不会让 ImageView 比其父级更宽:
  • 因此它的宽度将完全适合
  • 并且它将保持比例(由于 wrap_content)
我通常计算分辨率为 1080x1092(fullHD)的手机。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接