【Android Studio】ImageButton src属性とbackground属性の違い

ボタンに画像を表示する ImageButton ウィジェットでは
- src 属性
- background 属性
のどちらかで画像を指定します。

background 属性を使うとボタンのサイズに合わせて画像が拡大・縮小されます。 (画像右側)
この記事では表示形式が少し異なる src 属性 と background 属性の違いを紹介します。
準備
開発環境
Android Studio | 4.2.1 |
---|---|
Android Emulator | Nexus 4 (API 30) |
minSdk | 16 |
targetSdk | 30 |
画像について
使う画像は drawable フォルダに置いています。サイズは縦横 80 px にしています。

src 属性と background 属性の比較
ボタンのサイズを画像に合わせた場合

<!-- src:画像左側 -->
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/robot" />
<!-- background:画像右側 -->
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/robot" />
src 属性では padding が付くので、画像の周りがグレーになります。
padding=”0dp” を付けると background 属性と同じように表示されます。
参考:【Android Studio】ボタンに画像を表示する方法 – ImageButton ウィジェット
ボタンのサイズを画像より大きくした場合

<!-- src:画像左側 -->
<ImageButton
android:layout_width="120dp"
android:layout_height="120dp"
android:src="@drawable/robot" />
<!-- background:画像右側 -->
<ImageButton
android:layout_width="120dp"
android:layout_height="120dp"
android:background="@drawable/robot" />
src 属性の場合は画像がオリジナルのサイズで表示され、background 属性ではボタンのサイズにあわせて拡大されます。
ボタンのサイズを画像より小さくした場合

<!-- src:画像左側 -->
<ImageButton
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@drawable/robot" />
<!-- background:画像右側 -->
<ImageButton
android:layout_width="40dp"
android:layout_height="40dp"
android:background="@drawable/robot" />
src 属性の場合はオリジナルのサイズの画像がクロップされ、background 属性ではボタンのサイズにあわせて縮小されます。
src 属性の調整方法は以下の記事をお読み下さい。
参考:【Android Studio】ボタンに画像を表示する方法 – ImageButton ウィジェット
ボタンのサイズを横長にした場合

<!-- src:画像左側 -->
<ImageButton
android:layout_width="120dp"
android:layout_height="60dp"
android:src="@drawable/robot" />
<!-- background:画像右側 -->
<ImageButton
android:layout_width="120dp"
android:layout_height="60dp"
android:background="@drawable/robot" />
ボタンのサイズを縦長にした場合

<!-- src:画像左側 -->
<ImageButton
android:layout_width="60dp"
android:layout_height="120dp"
android:src="@drawable/robot" />
<!-- background:画像右側 -->
<ImageButton
android:layout_width="60dp"
android:layout_height="120dp"
android:background="@drawable/robot" />