Display SVG with Coil — Jetpack Compose

Abhishek Pundir
Geek Culture
Published in
2 min readAug 14, 2021

As an android developer loading SVG images is a task that you will do day in and day out.

Using Coil Library, this task has been made highly efficient as Coil automatically handles network request, transformations, and caching.

If you want to know more about the coil library and how it works, refer to this blog post here.

  1. Importing Dependencies

In your build.gradle file, add these dependencies for Coil Library.

(The Version might be different at the time, which you can check from here.)

// Coil Library Dependencies
implementation "io.coil-kt:coil-compose:1.3.2"
implementation "io.coil-kt:coil-svg:1.3.2"

2. Getting the SVG Url

Coil has an SVGDecoder which helps us to show SVG images in our composables.

Let say we have a SVG link.

val svgLink = "https://restcountries.eu/data/aus.svg"

3. Image Loader

Now we need to define an image loader.

ImageLoaders are service objects that execute ImageRequests. They handle caching, data fetching, image decoding, request management, bitmap pooling, memory management, and more.

val imageLoader = ImageLoader.Builder(LocalContext.current)
.componentRegistry {
add(SvgDecoder(LocalContext.current))
}
.build()

4. Fetching the Image

Then whenever we want to use it we have to pass it to the CompositionLocalProvider. Inside it you define a painter, the rest is classic compose with Image.

CompositionLocalProvider(LocalImageLoader provides imageLoader) {
val painter = rememberImagePainter(svgLink)

Image(
painter = painter,
contentDescription = "SVG Image",
modifier = Modifier
.size(80.dp)
.clip(CircleShape),
contentScale = ContentScale.FillBounds
)
}

Here we looked at how we can show SVG images in our composables with just an SVGDecoder.

Next, we’ll explore some other Jetpack Compose related features.

Till then Happy Composing.

--

--