将ImageView(及其src)适应布局宽度,并使其高度成比例缩放。

11

你能帮我配置我的布局吗?我没有达到我想要的效果:

我将ImageView背景设置为红色以解释我想要的是什么:

图片的宽度小于布局的宽度。我想让图片按比例增长并保持其宽高比,直到达到第一张图片的宽高比(我用photoshop手动修改了它),但是当将width =“fill_parent”时,结果是第二张图片,同时将宽度和高度都设置为“fill_parent”时,结果是第三张图片。

我试图结合ScaleType,但没有成功

我该如何实现第一个选项?谢谢

输入图像描述

2个回答

14

在 XML 中使用 android:adjustViewBounds=true 属性来调整 ImageView 元素的大小。


这个问题通过扩展 ImageView 类在这里得到了解决。

Android ImageView 调整父元素高度和适应宽度


我创建了一个示例,它对我有效。这是 xml 布局文件:

<?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">
    <ImageView android:src="@drawable/hydrangeas"
        android:layout_height="wrap_content" android:id="@+id/imageView1"
        android:scaleType="centerInside"
        android:adjustViewBounds="true"
        android:background="@android:color/white"
        android:layout_width="wrap_content"/>

</LinearLayout>

fitCenter也适用,查看快照。
使用centerInside和adjustViewBounds="true"


我真的不理解adjustViewBounds是如何工作的,但我用它无法达到我的目标,你能否解释一下如何做到? - Addev
尝试使用scaletype=centerInside与之配合。 - Ron
1
嗨,我的情况也是这样,它不起作用。较小的图像没有被放大以适应父视图,但是一些边框被留下了。 - peter.bartos

2
请在您的ImageView标签中使用fit_center属性。
<ImageView ... android:scaleType="fitCenter" .. />

感谢您的快速回复。您是指android:scaleType="fitCenter"对吧?使用该选项和两个维度都设置为fill_parent,结果类似于图像3(图像位于中间)。例如,如果高度设置为“wrap_content”,则结果是图像2,其中可绘制对象位于中心(水平方向)。 - Addev
如果您正在使用LinearLayout,请为两个参数使用“wrap_content”,并添加android:layout_weight="1"。 - Marcos Vasconcelos

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