Infinito Nirone 7

白羽の矢を刺すスタイル

android:windowBackground に指定する BitmapDrawable の位置を指定するときに気をつけること

Android アプリで SplashScreen を作る場合、android:windowBackground をつかうことでレイアウトを読み込まなくてもスプラッシュ用の画像を表示できます。レイアウトを待たなくてもよいので、アプリの起動直後からスプラッシュ画像が見えてよい、というのが android:windowBackground を使う場合の利点ですが、このプロパティに指定できるのはレイアウトではなく Drawable Resource です。

多くの場合スプラッシュ用画像には png 等の画像ファイルを用意すると思いますが、android:windowBackground に直接その画像を設定すると、画面サイズにあわせて画像が引き伸ばされてしまいます。これを避けるには、別途 XML で Bitmap Drawable を用意し、それを android:windowBackground に設定します。XML を用意すると画像を複数重ねたりすることも柔軟にできるようになり便利ですが、いくつか注意が必要です。

背景が必要な場合は Layer Drawable を使う

背景に模様を入れたり、色をちょっと変えたいなどの場合には、Layer Drawable で背景と Bitmap を重ねます。

背景のレイヤでは、<item>android:gravity="fill"を設定しましょう。

<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:gravity="fill">
        <shape android:shape="rectangle">
            <solid android:color="@color/splash_background"/>
        </shape>
    </item>
    <item>
        <bitmap
            android:src="@drawable/splash_image"/>
    </item>
</layer-list>

引き伸ばしを避けるために gravity を指定する

LayerDrawable 内で Bitmap を引き伸ばさず自分で位置を決めて表示する場合<item><bitmap>双方にandroid:gravityを設定します。 <bitmap>android:gravityがないと、端末によっては引き伸ばされてしまいます。

<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:gravity="fill">
        <shape android:shape="rectangle">
            <solid android:color="@color/splash_background"/>
        </shape>
    </item>
    <item android:gravity="center">
        <bitmap
            android:src="@drawable/splash_image"
            android:gravity="center"/>
    </item>
</layer-list>