我经常遇到这个问题,如果不创建自定义布局,我拒绝相信它无法解决:
如何将视图与ImageView对齐,后者将缩放以匹配其父边界,但保持纵横比(缩放类型除了fitXY之外)。我假设你将adjustViewBounds设置为true,调整视图边界以匹配图像的实际大小(“如果希望ImageView调整其边界以保持其drawable的宽高比,请将此设置为true。 “)。但事实并非如此。如果图像必须按比例放大或缩小以适应其范围,那就没有什么不同。
看看这个布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
>
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="@drawable/square" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/imageView1"
android:layout_alignTop="@+id/imageView1"
android:text="@string/hello_world" />
</RelativeLayout>
此布局如下所示:
正如您所看到的那样,边界不会被调整,并且TextView与不正确的边界对齐。我创建了一个自定义布局来创建适当的边界,但也许我错过了一些东西,应该可以使用标准布局功能......
编辑:澄清:我正在寻找一种方法将TextView与实际图像对齐。与给定示例中的红色正方形相同。
答案 0 :(得分:1)
好的,所以已经三年了,很久以前你可能已经想到了这一点。但是当你指定adjustviewBounds = true时,你就在那里。您只需要同时将ImageView布局宽度和高度更改为wrap_content。
您的TextView IS正如您所要求的那样与ImageView对齐。如果您要为ImageView提供背景颜色,您会发现它与TextView占据的区域相同。只是根据您的要求,实际图像在视图中居中。
您可以继续使用scaleType = fitCenter或centerInside,具体取决于您的需求。无法裁剪或拉伸图像,TextView将保持对齐状态。
答案 1 :(得分:0)
如果您使用android:scaleType="centerCrop"
上的ImageView
怎么办?
图像将被裁剪以覆盖整个布局,但将保持纵横比。