Scale image keeping its aspect ratio in background

2019-01-16 23:08发布

How do I make a background image fit the view but keep its aspect ratio when using <bitmap /> as a background drawable XML? None of <bitmap>'s android:gravity values gives the desired effect.

9条回答
聊天终结者
2楼-- · 2019-01-16 23:32

If your bitmap is wider than it is tall, use android:gravity="fill_vertical". Otherwise, use android:gravity="fill_horizontal". This has a similar effect as using android:scaleType="centerCrop" on an ImageView.

<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:gravity="fill_vertical"
    android:src="@drawable/image" />

If you support multiple orientations, you can create one bitmap XML file in the drawable-port folder and the other in the drawable-land folder.

查看更多
可以哭但决不认输i
3楼-- · 2019-01-16 23:33

Using the method described by a.ch worked great for me except I used this scale type which worked much better for what I needed:

android:scaleType="centerCrop"

Here is a full list of available scale types: http://developer.android.com/reference/android/widget/ImageView.ScaleType.html

查看更多
Anthone
4楼-- · 2019-01-16 23:35

There is an easy way to do this from the drawable:

your_drawable.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:drawable="@color/bg_color"/>
    <item>
        <bitmap
            android:gravity="center|bottom|clip_vertical"
            android:src="@drawable/your_image" />
    </item>

</layer-list>

The only downside is that if there is not enough space, your image won't be fully shown, but it will be clipped, I couldn't find an way to do this directly from a drawable. But from the tests I did it works pretty well, and it doesn't clip that much of the image. You could play more with the gravity options.

Another way will be to just create an layout, where you will use an ImageView and set the scaleType to fitCenter.

Hope this information helps you achieve what you want.

查看更多
登录 后发表回答