9
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Android] CoilでIntrinsicSizeによる画像サイズ指定が効かない時の対処法

Last updated at Posted at 2025-12-09

この記事はand factory.inc Advent Calendar 2025 10日目の記事です。

前回は @Miyazun さんの[Android] Jetpack Glacneでネット上の画像を取得するでした。


Androidのアプリ開発にてCoilのAsyncImageのサイズが思った通りにいかないことがありました。
Modifierを色々調節してみたら上手くいったので備忘録として残しておこうかと思います。

困ったこと

coilのバージョン3.3.0にしたところ、AsyncImageで思うように画像サイズの指定が効かないことがありました。

やりたいこと

  • Rowで画像とテキストを横に並べて表示させる
  • 画像はアス比固定でテキストサイズの高さに応じて大きさを変えたい

問題のコード

@Composable
fun Hogehoge(
    modifier: Modifier = Modifier,
) {
    Row(
        modifier = modifier
            .height(IntrinsicSize.Min)
    ) {
        AsyncImage(
            model = ImageRequest.Builder(LocalContext.current)
                .data("https://example.com/image.jpg")
                .crossfade(true)
                .build(),
            modifier = Modifier
                .aspectRatio(40f / 70f),
            placeholder = painterResource(R.drawable.placeholder),
            contentScale = ContentScale.Crop
        )

        Text(
            text = "テキスト",
            contentDescription = "テキスト"
        )
        
        ......   
    }
}

上記のコードだと親要素のRowでIntrinsicSizeを指定して高さを決めているのにも関わらず、AsyncImageが高さ指定を無視して表示されてしまいました。

解決策

固定サイズを指定した上でaspectRatioを指定することによって、画像の表示が安定し、他要素のサイズによるリサイズ表示と両立できるようになりました(元々想定されていた挙動)。

@Composable
fun Hogehoge(
    modifier: Modifier = Modifier,
) {
    Row(
        modifier = modifier
            .height(IntrinsicSize.Min)
    ) {
        AsyncImage(
            model = ImageRequest.Builder(LocalContext.current)
                .data("https://example.com/image.jpg")
                .crossfade(true)
                .build(),
            modifier = Modifier
                .aspectRatio(40f / 70f) //aspectRatioを指定した上で
                .width(40.dp) //画像サイズを指定
                .height(70.dp), //画像サイズを指定
            placeholder = painterResource(R.drawable.placeholder),
            contentScale = ContentScale.Crop
        )

        Text(
            text = "テキスト",
            contentDescription = "テキスト"
        )
            
        ......            
    }
}

解決策のコードだと、本来ならば 70×40 のサイズ固定のAsyncImageが表示されるはずなので謎ではあります🤔

9
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?