Member-only story
Android Kotlin code snippets — Coil Image loading
2 min readJan 16, 2025
Coil is a library to load images https://coil-kt.github.io/coil/. This article show how to display images in an Android app.
How to configure
Add the gradle dependencies
implementation("io.coil-kt.coil3:coil-compose:3.0.4")
implementation("io.coil-kt.coil3:coil-network-okhttp:3.0.4")
Code examples
Load Image
@Composable
fun LoadImage() {
// Coil load image
AsyncImage(
modifier = Modifier.wrapContentSize(),
model = "https://media.themoviedb.org/t/p/w440_and_h660_face/czembW0Rk1Ke7lCJGahbOhdCuhV.jpg",
contentDescription = "Image",
error = painterResource(resource = Res.drawable.compose_multiplatform)
)
}
Logic to add offline caching
fun getAsyncImageLoader(context: PlatformContext) =
ImageLoader.Builder(context)
.memoryCachePolicy(CachePolicy.ENABLED)
.memoryCache {
MemoryCache.Builder().maxSizePercent(
context, 0.3
)
.strongReferencesEnabled(true)
.build()
}
.diskCachePolicy(CachePolicy.ENABLED)
.networkCachePolicy(CachePolicy.ENABLED)
.diskCache {
newDiskCache()
}
.crossfade(true).logger(DebugLogger()).build()
fun newDiskCache(): DiskCache {
return DiskCache.Builder().directory(FileSystem.SYSTEM_TEMPORARY_DIRECTORY /…