アプリ開発備忘録

PlayStationMobile、Android、UWPの開発備忘録

【Android】Jetpack Composeの画像読み込みと加工のバットプラクティス

※追記

デバッグビルドと本番ビルド、端末ごとにパフォーマンスが大きく異る事がわかったので、パフォーマンスが悪いのはそれのせいかもしれません。(特に自分はPixel5でパフォーマンスが悪かったです。Pixel3は問題なかったですが。)

前提

rc01が出ていますが、プレビュー用のライブラリのパッケージが移動して、Android Studioがプレビューに対応していない為、 1.0.0-beta09 を使用しています。

implementation "com.google.accompanist:accompanist-coil:0.12.0"

ライブラリ

ネットワークからの画像読み込みライブラリはPicasso, Glide, Coil等がありますが、ComposeでGoogleが公式に対応しているのはGlideとCoilです。(そもそもPiassoはメンテナンスしかされない)

その2つでも、推しているのはCoilの方です。
GlideのCompose統合のページを見ると、Coilを使用してくださいとあります。

Tip Unless you have a specific requirement to use Glide, consider using Coil instead. Coil is built upon Kotlin Coroutines which means that it integrates better with Jetpack Compose, which also heavily uses Coroutines. https://google.github.io/accompanist/glide/

画像読み込みと加工

このような円形で、周りが縁取られているデザインを考えます。
f:id:matsudamper:20210705080052p:plain:w200

画像はAccompanistのおかげで rememberCoilPainterPainterを取得するだけなので楽です。
Modifier で画像を加工していますが、これはパフォーマンスが悪いです。

Image(
    modifier = Modifier
        .width(100.dp)
        .aspectRatio(1f)
        .border(1.dp, MaterialTheme.colors.background, CircleShape)
        .clip(CircleShape),
    contentScale = ContentScale.Crop,
    painter = rememberCoilPainter(
        request = url,
    ),
    contentDescription = "icon"
)

Modifier で画像を加工するのはパフォーマンスが悪いため、Surface を使用します。

Surface(
    modifier = Modifier
        .width(100.dp)
        .aspectRatio(1f),
    border = BorderStroke(1.dp, MaterialTheme.colors.background),
    shape = CircleShape
) {
    Image(
        contentScale = ContentScale.Crop,
        painter = rememberCoilPainter(
            request = url,
        ),
        contentDescription = null
    )
}

おわりに

この例を貼り付けただけでは特にパフォーマンスの問題は感じられませんでしたが、ConstraintLayoutの中に入れたり、ViewModelを実際に使用していたらかなりパフォーマンスが悪くて、スクロールでガタつきました。