Jetpack Compose Load Image With Coil

Edit Module's build.gradle

dependencies {
  implementation "io.coil-kt:coil-compose:1.4.0"
}

Add permission to AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="...">

    <uses-permission android:name="android.permission.INTERNET" />

</manifest>

Sample Code

Load Image

Image(    painter = rememberImagePainter("https://picsum.photos/id/237/200/300"),    contentDescription = "Black Dog",    modifier = Modifier.size(128.dp))

Load image with

  • Placeholder
  • Transition
  • Error image
  • Scale/Crop image to fully fit view
val painter = rememberImagePainter(    data = "https://picsum.photos/id/237/200/300",    builder = {        placeholder(R.drawable.placeholder)        // transition when placeholder -> image        crossfade(true)        error(R.drawable.error)    })Image(    painter = painter,    contentDescription = null,    modifier = Modifier.size(128.dp),    contentScale = ContentScale.Crop)

Maintain aspect ratio and crop/scale to fit

Image(    painter = painter,    contentDescription = null,    modifier = modifier.aspectRatio(1.0f),     contentScale = ContentScale.Crop)

Load 3 Grid Images per row

@Composablefun SampleScreen() {    val rowSize = 3    LazyColumn {        (1..10).chunked(rowSize) { imageIds ->            Row {                for ((index, imageId) in imageIds.withIndex()) {                    val url = "https://picsum.photos/id/$imageId/200/300"                    PhotoItem(                        modifier = Modifier.fillMaxWidth(1f / (rowSize - index)),                        data = url                    )                }            }        }    }}@Composablefun PhotoItem(modifier: Modifier, data: Any) {    val painter = rememberImagePainter(        data = data,        builder = {            placeholder(R.drawable.placeholder)            // transition when placeholder -> image            crossfade(true)            error(R.drawable.error)        }    )    Image(        painter = painter,        contentDescription = null,        modifier = modifier.aspectRatio(1.0f),        contentScale = ContentScale.Crop    )}

NOTE: Alternatively you could use LazyVerticalGrid

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.