【问题标题】:align view to a scaled ImageView将视图与缩放的 ImageView 对齐
【发布时间】:2013-12-14 09:45:22
【问题描述】:

我经常遇到这个问题,我拒绝相信不创建自定义布局就无法解决:

如何将视图与缩放以匹配其父边界但保持纵横比的 ImageView 对齐(缩放类型不是 fitXY )。我假设如果您将 adjustViewBounds 设置为 true,则视图边界会被调整以匹配图像的实际大小(“如果您希望 ImageView 调整其边界以保持其可绘制对象的纵横比,请将其设置为 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 与实际图像对齐的方法。这就是给定示例中的红色方块。

【问题讨论】:

  • 当您尝试使用 android:background="@drawable/square" 时会发生什么?
  • “如何将视图与 ImageView 对齐”,那么您的实际意思是什么?
  • 您的 TextView 已根据您在 xml -alignRight 和 alirnTop 中的规范正确对齐。您希望在何处以及如何对齐。
  • 我想将文本视图与实际图像对齐。

标签: android android-layout imageview alignment adjustviewbounds


【解决方案1】:

好的,已经三年了,您可能很久以前就想到了这一点。但是当您指定adjustviewBounds=true 时,您已经完成了一半。您只需要将 ImageView 布局的宽度和高度同时更改为 wrap_content 即可。

您的 TextView 正按照您的要求与您的 ImageView 对齐。如果您要为 ImageView 提供背景颜色,您会看到它与 TextView 占据相同的区域。只是实际图像按照您的要求在视图中居中。

您可以根据需要继续使用 scaleType=fitCenter 或 centerInside。两者都不会裁剪或拉伸图像,并且您的 TextView 将保持对齐。

【讨论】:

    【解决方案2】:

    如果您在 ImageView 上使用 - android:scaleType="centerCrop" 会怎样? 图像将被裁剪以覆盖整个布局,但将保持纵横比。

    【讨论】:

    • 如果你指定centerCrop,如果图像小于父容器,图像将不会被放大。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-11
    • 1970-01-01
    • 2011-08-05
    • 2021-11-01
    • 2021-10-23
    相关资源
    最近更新 更多