【Android Studio】ボタンに画像を表示する方法 – ImageButtonビュー
![](https://codeforfun.jp/wp-content/uploads/2021/07/thumb-as-image-button-widget.png)
この記事ではボタンに画像を表示する ImageButtonビューの使い方を紹介します。
![](https://codeforfun.jp/wp-content/uploads/2021/07/as-image-button-widget-1.png)
画像とテキストを表示するボタンの作り方は以下の記事をお読み下さい。
![](https://codeforfun.jp/wp-content/uploads/2021/07/as-button-text-and-image-4.png)
準備
開発環境
Android Studio | 4.2.1 |
---|---|
Android Emulator | Nexus 4 (API 30) |
minSdk | 16 |
targetSdk | 30 |
画像について
使う画像は drawable フォルダに置いています。サイズは縦横 80 px にしています。
![](https://codeforfun.jp/wp-content/uploads/2021/07/as-image-button-widget-2.png)
ImageButtonビューの使い方
ボタンのサイズを wrap_content にした場合
![](https://codeforfun.jp/wp-content/uploads/2021/07/as-image-button-widget-3.png)
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/robot" />
グレーの部分を無くす場合は padding 属性を追加します。
![](https://codeforfun.jp/wp-content/uploads/2021/07/as-image-button-widget-4.png)
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/robot"
android:padding="0dp" />
ボタンのサイズを画像より大きくした場合
![](https://codeforfun.jp/wp-content/uploads/2021/07/as-image-button-widget-5.png)
<ImageButton
android:layout_width="150dp"
android:layout_height="150dp"
android:src="@drawable/robot" />
ボタンのサイズに合わせて画像を拡大するには scaleType 属性を使います。
![](https://codeforfun.jp/wp-content/uploads/2021/07/as-image-button-widget-6.png)
<ImageButton
android:layout_width="150dp"
android:layout_height="150dp"
android:src="@drawable/robot"
android:scaleType="fitCenter" />
ボタンのサイズを画像より小さくした場合
![](https://codeforfun.jp/wp-content/uploads/2021/07/as-image-button-widget-7.png)
<ImageButton
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@drawable/robot" />
ボタンのサイズに合わせて画像を表示するには scaleType 属性を使います。
![](https://codeforfun.jp/wp-content/uploads/2021/07/as-image-button-widget-8.png)
<ImageButton
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@drawable/robot"
android:scaleType="fitCenter"
android:padding="0dp" />
src 属性で画像を指定すると画像はオリジナルのサイズで表示されます。background 属性を使うとボタンのサイズに合わせて画像が拡大・縮小されます。
参考:ImageButton の src 属性と background 属性の違い