【Android】Jetpack Composeで画像リソース(Drawable)を表示する方法
この記事からわかること
- Kotlin/Android Jetpack Composeの使い方
- 画像リソース(Drawableなど)の表示方法
- painterResource関数とImageVector.vectorResourceの使い方
index
[open]
\ アプリをリリースしました /
環境
- Android Studio:Narwhal Feature Drop
- Android OS:15以降
- Kotlin:2.2.21
- Material3
- AGP:8.12.3
- Gradle:8.13
- macOS(M1):Tahoe 26.0.1
Composeで画像リソースを表示する方法
ComposeでUIを構築している場合に画像リソース(DrawableやBitmap(png/jpgなど)、Vector)を表示する方法はImageとIconのどちらかを使う方法があります。ただどちらにせよ画像リソースを取得してくる必要があり、それはpainterResourceで可能になっています。
painterResource関数は引数に取得したいリソースのIDを渡し、返り値としてPainter型で画像リソースを取得することができます。Painter型はComposeで画像を描画するための抽象クラスです。
painterResource(R.drawable.my_icon)
ImageとIconの使い分け
先行してImageとIconの使い分けの基準を整理しておきます。
| Image | Icon | |
|---|---|---|
| 目的 | 画像表示 | アイコン表示 |
| サイズ | 自由 | Material Designに則った24.dpが推奨 |
| 色調整 | 自由(※) | 自由(※) |
※ 画像リソースの色を調整できるのは基本的に「ImageVector (Material Icons)」や「VectorDrawable (XML vector)」に限定されます。Bitmap形式(pngやjpgなど)のものはtintで色を指定しても変化しないので注意してください。
Imageで画像リソースを表示する
Image関数で表示させたい場合は引数painterにpainterResourceで画像リソースを取得して指定します。
Image(
painter = painterResource(R.drawable.my_icon),
contentDescription = null,
modifier = Modifier.size(20.dp)
)
また「ImageVector (Material Icons)」を指定したい場合は引数imageVectorを使用します。
Image(
imageVector = Icons.Default.PlayArrow,
contentDescription = "再生",
modifier = Modifier.size(20.dp)
)
色を調整する
色を調整したい場合はColorFilter.tintを使用します。Imageでは特に指定しない場合画像リソースの色味がそのまま表示されます。
Image(
painter = painterResource(R.drawable.my_icon),
contentDescription = null,
modifier = Modifier.size(20.dp),
colorFilter = ColorFilter.tint(Color.Red)
)
画像の拡大・縮小
画像の拡大・縮小などを行いたい場合はContentScaleを使用します。
Image(
painter = painterResource(R.drawable.my_icon),
contentDescription = null,
modifier = Modifier.size(20.dp),
// 中央を拡大して切り抜き
contentScale = ContentScale.Crop
)
ContentScaleは7種類定義されています。
- ContentScale.Fit・・・拡大・縮小して全体を表示(アスペクト比維持)
- ContentScale.FillBounds・・・余白なし・比率無視
- ContentScale.Crop・・・中央を拡大して切り抜き
- ContentScale.FillHeight・・・高さを優先して合わせる
- ContentScale.FillWidth・・・幅を優先して合わせる
- ContentScale.Inside・・・縮小して全体を表示(アスペクト比維持)
- ContentScale.None・・・拡大縮小しない
Iconで画像リソースを表示する
Icon関数で表示させたい場合も引数painterにpainterResourceで画像リソースを取得して指定します。Iconではデフォルトのサイズが24.dpに指定されているため特に指定しなければ推奨サイズになります。
Image(
painter = painterResource(R.drawable.my_icon),
contentDescription = null,
)
また「ImageVector (Material Icons)」を指定したい場合は引数imageVectorを使用します。
Icon(
imageVector = Icons.Default.PlayArrow,
contentDescription = "再生",
)
色を調整する
色を調整したい場合は引数tintにカラーを指定します。Iconではtintで明示的にカラーを指定しないと黒色になります。
Icon(
imageVector = Icons.Default.PlayArrow,
contentDescription = "再生",
tint = Color.Black
)
まだまだ勉強中ですので間違っている点や至らぬ点がありましたら教えていただけると助かります。
ご覧いただきありがとうございました。







