固定大小的ImageView,不受图片大小影响

15
我有一个ImageView,我希望它始终保持相同的大小。如果图像小于视图,则希望它居中显示。如果图像大于视图,则需要缩小,同时保持纵横比。
我已经尝试了几次,最新的尝试如下:
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <ImageView android:id="@+id/itemImage" android:layout_width="100dp"
            android:layout_height="100dp" android:scaleType="fitCenter"
            android:adjustViewBounds="true" android:gravity="center" android:padding="10px" />
  <TextView android:id="@+id/currentLentItem" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:padding="10px"/>
</LinearLayout>

我这里漏掉了什么?


你是否得到了一个令人满意的解决方案? - nwaltham
2个回答

11

如果图片比视图大,那么你可以使用以下方式进行缩放:

android:scaleType="fitXY" 

如果图像比较小,那么这不会得到你想要的结果。也许你可以在运行时检测并以编程方式更改scaleType。


1
imageView.setScaleType(ScaleType.FIT_XY); - Ajay Pandya

11

尝试使用缩放类型centerInside,例如:

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        >
    <ImageView
        android:id="@+id/itemImage"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignParentRight="true"
        android:scaleType="centerInside"
        android:gravity="right|center_vertical"
        android:padding="10px"
        />
    <TextView
        android:id="@+id/currentLentItem"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_toLeftOf="@id/list_image"
        android:padding="10px"
        />
</RelativeLayout>
如果图像大于布局,则此代码会将其缩小,并且它也会按比例缩放(而fitXY则不考虑纵横比)。如果图像较小,则它还会将其居中。
编辑:我已经更新了示例以获取您想要的内容。以下是更改的要点:
• ImageView重力更改为right|center_vertical。由于您希望它们在右侧对齐,因此即使它们是纵向方向图像,使用此重力也将允许对齐。
• ImageView对齐到RelativeLayout的右侧
• RelativeLayout设置为wrap_content,因为它将用于ListView。
• 添加TextView,对齐到父元素的左侧,并通过itemImage的左侧定义其右边缘。

谢谢你的帮助,看起来好多了。不过视图似乎仍然没有固定大小。正如你在上面的例子中所看到的,ImageView 旁边是一个 TextView,并且这些都显示在 ListView 中。我希望每个 ImageView 的右边缘都对齐,以便一切看起来整洁和统一... - Paul Hunnisett
Paul,我添加了一个更新的例子让你尝试;这应该可以让你更接近你所寻找的东西。 - Kevin Coppock
谢谢。但是ImageViews的大小仍然不同。我需要它们的宽度完全相同。我本以为设置layout_width可以做到这一点,但显然并不行... - Paul Hunnisett
1
你的ImageViews大小相同,它们内部的内容会发生变化。如果它们都必须具有相同的宽度,则需要使用类似于centerCrop或fitCenter的东西来进行缩放类型。据我所知,如果它们小于100dp,则您不希望对它们进行缩放,但是如果您希望它们缩放到恰好100dp,则应使用fitCenter。当您拥有纵向方向的图像时,这就成为了一个问题。FitCenter将起作用,但高度将为100dp,宽度将成比例缩小...(续) - Kevin Coppock
1
这是你可能想要使用 centerCrop 的时候(我非常确定 centerCrop 是我想到的那个)。它将使最小的一边适应容器,但是你最长的一边将被裁剪以适应容器。基本上,如果你没有纵向定向的图像,fitCenter 就可以解决问题。如果你有纵向图像,你要么必须裁剪,要么高度会有所不同。 - Kevin Coppock
如果您访问http://www.monkeypower.co.uk/screenie.png,您可以看到当前的屏幕截图。您可以看到底部3个TextView比顶部两个宽。我想要的是所有视图彼此之间排列得整齐...我尝试了centerCrop-实际上,这就是屏幕截图中的内容。 - Paul Hunnisett

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