Phuc VR
1 supporter
How to use Coil For Jetpack Compose

How to use Coil For Jetpack Compose

Dec 15, 2022

Bild

Like the previous video I did about "How to use Glide in Jetpack Compose". Next, I continue with the topic of how to use coils in Jetpack compose.

First, we to add support for Jetpack Compose, import the extension library:

implementation("io.coil-kt:coil-compose:2.2.2")

You must first apply for internet access in mainifest:

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

Then use the AsyncImage composable to load and display an image:

@Composable
fun LoadingImage(path: String) {
    AsyncImage(
        model = path,
        contentDescription = "Image"
    )
}

model can either be the ImageRequest.data value - or the ImageRequest itself. contentDescription sets the text used by accessibility services to describe what this image represents.

AsyncImage

AsyncImage is a composable that executes an image request asynchronously and renders the result. It supports the same arguments as the standard Image composable and additionally, it supports setting placeholder/error/fallback painters and ing/onSuccess/ callbacks. Here's an example that loads an image with a circle crop, crossfade, erorr, and sets a placeholder:

AsyncImage(model = ImageRequest.Builder(LocalContext.current)
    .data(name)
    .crossfade(true)
    .build(),
    placeholder = painterResource(id = R.drawable.ic_launcher_background),
    error = painterResource(id = R.drawable.ic_launcher_foreground),
    contentScale = ContentScale.Crop,
    modifier = Modifier.clip(CircleShape),
    contentDescription = "NickSeven")

Great isn't it, we have successfully loaded an image from the internet, you can see that the image has been scaled and cut off the excess in a circle.

Gefällt dir dieser Beitrag?

Kaufe Phuc VR einen Kaffee

Mehr von Phuc VR