Advertisement

Responsive Advertisement

Image Loading from url in android jetpack compose using Coil library

  •  Step 1

    implementation("io.coil-kt:coil-compose:2.7.0")
    If any issue coming related gradle issue
    composeOptions {
    kotlinCompilerExtensionVersion '1.5.15'
    }
    id 'org.jetbrains.kotlin.android' version '1.9.25' apply false
  • Step 2

    @Composable
    fun CoilImage() {
    val grayscaleMatrix = ColorMatrix().apply {
    setToSaturation(0f) // Set saturation to 0 to make the image grayscale
    }

    Box(
    modifier = Modifier.size(100.dp), // Adjusted size for visualization
    contentAlignment = Alignment.Center
    ) {
    val painter = rememberAsyncImagePainter(
    model = ImageRequest.Builder(LocalContext.current)
    .data("https://th.bing.com/th/id/OIP.vV7JR7eGaRUwzAbFcYFzkAHaHa?rs=1&pid=ImgDetMain")
    .placeholder(R.drawable.ic_launcher_background)
    .error(R.drawable.ic_google_logo)
    .crossfade(true) // Enable crossfade animation
    .build()
    )
    val painterState = painter.state

    Image(
    painter = painter,
    contentDescription = "Logo image",
    contentScale = ContentScale.Crop, // Use Crop to fill the rounded shape
    modifier = Modifier
    .size(100.dp) // Adjusted size for better visualization
    .clip(CircleShape), // Clip the image to a circle shape
    colorFilter = ColorFilter.colorMatrix(grayscaleMatrix) // Apply grayscale filter
    )

    if (painterState is AsyncImagePainter.State.Loading) {
    CircularProgressIndicator()
    }
    }
    }

    @Preview(showBackground = true)
    @Composable
    fun PreviewCoilImage() {
    CoilImage()
    }
  • Step 3 

     Screenshot 




Post a Comment

0 Comments