如何在 ImageView 中缩放图像以保持纵横比

问题描述:

在 Android 中,我将 ImageViewlayout_width 定义为 fill_parent(占据手机的整个宽度).

In Android, I defined an ImageView's layout_width to be fill_parent (which takes up the full width of the phone).

如果我放入 ImageView 的图像大于 layout_width,Android 会缩放它,对吗?但是身高呢?Android 缩放图片时,会保持纵横比吗?

If the image I put to ImageView is bigger than the layout_width, Android will scale it, right? But what about the height? When Android scales the image, will it keep the aspect ratio?

我发现当 Android 缩放比 ImageView 大的图像时,ImageView 的顶部和底部有一些空白.真的吗?如果是,我怎样才能消除那个空白?

What I find out is that there is some white space at the top and bottom of the ImageView when Android scales an image which is bigger than the ImageView. Is that true? If yes, how can I eliminate that white space?

  1. 是的,默认情况下,Android 会缩小您的图像以适合 ImageView,同时保持纵横比.但是,请确保您使用 android:src=..." 而不是 android:background=..." 将图像设置为 ImageView代码>.src= 使它缩放图像保持纵横比,但 background= 使它缩放 扭曲图像以使其完全适合尺寸的图像视图.(不过,您可以同时使用背景和源,这对于在主图像周围显示框架等操作非常有用,仅使用一个 ImageView.)

  1. Yes, by default Android will scale your image down to fit the ImageView, maintaining the aspect ratio. However, make sure you're setting the image to the ImageView using android:src="..." rather than android:background="...". src= makes it scale the image maintaining aspect ratio, but background= makes it scale and distort the image to make it fit exactly to the size of the ImageView. (You can use a background and a source at the same time though, which can be useful for things like displaying a frame around the main image, using just one ImageView.)

您还应该看到 android:adjustViewBounds 使 ImageView 调整自身大小以适应重新缩放的图像.例如,如果您在通常为方形 ImageView 的地方有一个矩形图像,则 adjustViewBounds=true 会将 ImageView 的大小也调整为矩形.这会影响其他 Views 在 ImageView 周围的布局.

You should also see android:adjustViewBounds to make the ImageView resize itself to fit the rescaled image. For example, if you have a rectangular image in what would normally be a square ImageView, adjustViewBounds=true will make it resize the ImageView to be rectangular as well. This then affects how other Views are laid out around the ImageView.

然后如 Samuh 所写,您可以使用 android:scaleType 参数更改默认缩放图像的方式.顺便说一下,发现它是如何工作的最简单的方法就是自己尝试一下!请记住查看模拟器本身(或实际手机)中的布局,因为 Eclipse 中的预览通常是错误的.

Then as Samuh wrote, you can change the way it default scales images using the android:scaleType parameter. By the way, the easiest way to discover how this works would simply have been to experiment a bit yourself! Just remember to look at the layouts in the emulator itself (or an actual phone) as the preview in Eclipse is usually wrong.