【Android】Jetpack Composeで画像リソース(Drawable)を表示する方法

【Android】Jetpack Composeで画像リソース(Drawable)を表示する方法

この記事からわかること

  • Kotlin/Android Jetpack Compose使い方
  • 画像リソース(Drawableなど)の表示方法
  • painterResource関数ImageVector.vectorResourceの使い方

index

[open]

\ アプリをリリースしました /

みんなの誕生日

友達や家族の誕生日をメモ!通知も届く-みんなの誕生日-

posted withアプリーチ

環境

Composeで画像リソースを表示する方法

ComposeでUIを構築している場合に画像リソース(DrawableやBitmap(png/jpgなど)、Vector)を表示する方法ImageIconのどちらかを使う方法があります。ただどちらにせよ画像リソースを取得してくる必要があり、それはpainterResourceで可能になっています。

painterResource関数は引数に取得したいリソースのIDを渡し、返り値としてPainter型で画像リソースを取得することができます。Painter型はComposeで画像を描画するための抽象クラスです。

painterResource(R.drawable.my_icon)

ImageとIconの使い分け

先行してImageIconの使い分けの基準を整理しておきます。

Image Icon
目的 画像表示 アイコン表示
サイズ 自由 Material Designに則った24.dpが推奨
色調整 自由(※) 自由(※)

※ 画像リソースの色を調整できるのは基本的に「ImageVector (Material Icons)」や「VectorDrawable (XML vector)」に限定されます。Bitmap形式(pngやjpgなど)のものはtint色を指定しても変化しないので注意してください。

Imageで画像リソースを表示する

Image関数で表示させたい場合は引数painterpainterResourceで画像リソースを取得して指定します。

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種類定義されています。

Iconで画像リソースを表示する

Icon関数で表示させたい場合も引数painterpainterResourceで画像リソースを取得して指定します。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
)

まだまだ勉強中ですので間違っている点や至らぬ点がありましたら教えていただけると助かります。

ご覧いただきありがとうございました。

Search Box

Sponsor

ProFile

ame

趣味:読書,プログラミング学習,サイト制作,ブログ

IT嫌いを克服するためにITパスを取得しようと勉強してからサイト制作が趣味に変わりました笑今はCMSを使わずこのサイトを完全自作でサイト運営中〜

New Article

index