Search code examples
androidandroid-jetpack-composecoil

How to load image using AsyncImage in jetpack compose with GrayScale transformation?


I am unable to achieve the grayscale transformation.

Current code to load Image.

AsyncImage(
    model = ImageRequest.Builder(LocalContext.current)
        .data(url)
        .crossfade(true)
        .build(),
    contentDescription = "",
    contentScale = ContentScale.Crop,
    modifier = Modifier
        .size(44.dp)
        .clip(CircleShape),
)

The code I found for GrayScale transformation uses rememberImagePainter which is deprecated.

How to achieve this using rememberAsyncImagePainter or AsyncImage?


Solution

  • You can apply the colorFilter attribute:

    val matrix = ColorMatrix()
    matrix.setToSaturation(0F)
    
    AsyncImage(
        model = ImageRequest.Builder(LocalContext.current)
            .data(url)
            .crossfade(true)
            .build(),
        contentDescription = "",
        contentScale = ContentScale.Crop,
        modifier = Modifier
            .size(44.dp)
            .clip(CircleShape),
        colorFilter = ColorFilter.colorMatrix(matrix)
    )