アンドロイドのバックグラウンド画像を、自動的にサイズ調整する方法
Android の背景画像に自動で適応させるには、次の方法を使用できます。
- アンドロイドのスケールタイプ
- fitXY:画像はビューのサイズに合わせて拡大縮小されるため、アスペクト比が崩れる可能性があります。
- 画像の元の縦横比のまま、Viewの左上に配置する
- 画像の元の比率に合わせて縮小・拡大し、画面の中央に配置します。
- fitEnd: 画像の比率を保持してViewの右下に表示します。
- 日本語に翻訳すると以下のようになります。
たとえば、以下のファイルを置いていきます。
- res/drawable-mdpi/background.png:密度が低い画面 (mdpi) 用の背景画像
- res/drawable-hdpi/background.png:中密度画面(hdpi)用の背景画像
- res/drawable-xhdpi/background.png: 高密度画面 (xhdpi) 用の背景画像
Androidはデバイスの画面密度に応じ自動的に適切な画像リソースを選択します。
- 制約レイアウト
- 彼は日本人の友達に日本語を勉強してもらった。
- app:layout_constraintDimensionRatio
例としてあげるなら:
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background_image">
<ImageView
android:layout_width="0dp"
android:layout_height="0dp"
android:scaleType="centerCrop"
android:src="@drawable/background_image"
app:layout_constraintDimensionRatio="3:2"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
上記の例では、ConstraintLayoutをルートレイアウトとして使用し、背景画像がレイアウト全体の背景として設定されています。 ImageViewは子ビューとして、layout_widthとlayout_heightを0dpに設定し、layout_constraintDimensionRatioを使用して縦横比を指定することで、サイズの大画面への追従を実現しています。