简体   繁体   中英

How to keep background aspect ratio on different screens

I prepared a background image for my application in Galaxy S9+ screen ratio (almost 2:1), such that it will be big enough for all screen sizes. Then I defined the background drawable in the following way:

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/background"
    android:gravity="fill_horizontal"
    android:tileMode="disabled">
</bitmap>

Then I use it as follows:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:bind="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".activities.GameActivity">

    <data>

        <variable
            name="viewModel"
            type="..." />
    </data>

    <FrameLayout
        android:id="@+id/g_viewPlaceholder"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="@drawable/activity_background">

    </FrameLayout>
</layout>

When I run application on devices with ratio similar to SGS9+, background seems to be correct. However, when I run the app on, say Galaxy S6 with screen ratio 16:9, background is vertically compressed (even though bottom and top parts are cut off - as designed).

How can I set up the background to be stretched horizontally and cut off vertically, but so that aspect ratio will be kept?

Try this code below.

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/background"
android:gravity="clip_vertical|fill_horizontal"
android:tileMode="disabled">
</bitmap>

If this won't work, try tweaking Layout Gravity to clip vertically

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM