How to scale an Image in ImageView to keep the aspect ratio

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

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?

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?


  • 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.)

  • 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.

    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.


  • See android:adjustViewBounds .

    Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable.


    To anyone else having this particular issue. You have an ImageView (or other View ) that you want to have a width of fill_parent and a height scaled proportionately:

    Add these two attributes to your ImageView :

    android:adjustViewBounds="true"
    android:scaleType="centerCrop"
    

    And set the ImageView width to fill_parent and height to wrap_content .

    Also, if you don't want your image to be cropped, try this:

     android:adjustViewBounds="true"
     android:layout_centerInParent="true"
    
    链接地址: http://www.djcxy.com/p/50282.html

    上一篇: 调整/缩放位图后图像质量不佳

    下一篇: 如何在ImageView中缩放图像以保持纵横比