Coil simplifies image loading in Compose. Learn AsyncImage, caching strategies, and SubcomposeAsyncImage for advanced use cases.
Basic AsyncImage Usage
Load and display images with one line:
AsyncImage(
model = "https://example.com/image.jpg",
contentDescription = "Profile picture",
modifier = Modifier
.size(128.dp)
.clip(CircleShape),
contentScale = ContentScale.Crop
)
Configuring Image Loading with ImageRequest
Customize loading behavior:
val imageRequest = ImageRequest.Builder(context)
.data("https://example.com/image.jpg")
.crossfade(true)
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.build()
AsyncImage(
model = imageRequest,
contentDescription = "Article image",
modifier = Modifier.fillMaxWidth(),
contentScale = ContentScale.Crop
)
Custom Caching Strategy
Optimize memory and disk usage:
// In Application class
val imageLoader = ImageLoader.Builder(context)
.memoryCache {
MemoryCache.Builder(context)
.maxSizePercent(0.25) // Use 25% of memory
.build()
}
.diskCache {
DiskCache.Builder()
.directory(File(context.cacheDir, "image_cache"))
.maxSizeBytes(100 * 1024 * 1024) // 100 MB
.build()
}
.build()
Coil.setImageLoader(imageLoader)
SubcomposeAsyncImage for Complex Layouts
Handle loading, success, and error states:
SubcomposeAsyncImage(
model = "https://example.com/image.jpg",
contentDescription = "Product image",
modifier = Modifier.fillMaxSize()
) { state ->
when (state) {
is AsyncImagePainter.State.Loading -> {
CircularProgressIndicator()
}
is AsyncImagePainter.State.Success -> {
Image(
painter = state.painter,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop
)
}
is AsyncImagePainter.State.Error -> {
Icon(Icons.Default.Error, "Error loading image")
}
}
}
Coil's efficient loading and caching improve app performance. Use SubcomposeAsyncImage when you need custom loading states.
8 Android app templates on Gumroad
Top comments (0)