无论位图的大小如何,我如何使ImageView成为固定大小

时间:2022-05-26 21:28:12

So I'm loading images from a web service, but the size of the images are sometimes smaller or bigger than other images and the visualization looks silly when I put them in a ListView in android. I'd like to fix the size of my ImageView so that it only shows a portion of the image if it's larger than a preset amount. I've tried everything I can think of setting the setMaxWidth/setMaxHeight, setting the scale type to centerCrop, using ClipableDrawable wrapping my BitmapDrawable, setting using Drawable.setBounds(). I've tried setting in the XML and programmatically, but neither worked. I'm very surprised setting max width/height didn't do anything. Below is the XML I'm using ImageView definition in my layout file:

所以我正在从Web服务加载图像,但是图像的大小有时比其他图像更小或更大,当我将它们放入android中的ListView时,可视化看起来很傻。我想修改我的ImageView的大小,以便它只显示图像的一部分,如果它大于预设量。我已经尝试了所有我能想到的设置setMaxWidth / setMaxHeight,将scale类型设置为centerCrop,使用ClipableDrawable包装我的BitmapDrawable,使用Drawable.setBounds()进行设置。我已尝试在XML中进行编程并设置,但都没有工作。我很惊讶设置最大宽度/高度没有做任何事情。下面是我在布局文件中使用ImageView定义的XML:

    <ImageView android:id="@+id/recipeImage"
           android:maxHeight="64px"
           android:maxWidth="64px"
           android:scaleType="centerCrop"
           android:layout_width="wrap_content"
           android:layout_height="fill_parent"
           android:layout_alignParentTop="true"
           android:layout_alignParentBottom="true"
           android:layout_marginRight="6dip"/>

But,nothing has worked.

但是,没有任何效果。

2 个解决方案

#1


42  

Just delete the maxHeight and maxWidth attributes and enter your units in layout_width and layout_height appropriately. But do not use the 'px' unit - use 'dp' instead, because these are device-independent.

只需删除maxHeight和maxWidth属性,并在layout_width和layout_height中相应地输入单位。但是不要使用'px'单位 - 改为使用'dp',因为它们与设备无关。

#2


0  

This will fit the image in the specified height and width, irrespective of image size.

无论图像大小如何,这都将使图像适合指定的高度和宽度。

<ImageView
        android:id="@+id/image5"
        android:layout_width="300dp"
        android:layout_height="200dp"
        android:src="@drawable/image_1"
        android:scaleType="fitXY"/>

#1


42  

Just delete the maxHeight and maxWidth attributes and enter your units in layout_width and layout_height appropriately. But do not use the 'px' unit - use 'dp' instead, because these are device-independent.

只需删除maxHeight和maxWidth属性,并在layout_width和layout_height中相应地输入单位。但是不要使用'px'单位 - 改为使用'dp',因为它们与设备无关。

#2


0  

This will fit the image in the specified height and width, irrespective of image size.

无论图像大小如何,这都将使图像适合指定的高度和宽度。

<ImageView
        android:id="@+id/image5"
        android:layout_width="300dp"
        android:layout_height="200dp"
        android:src="@drawable/image_1"
        android:scaleType="fitXY"/>