Home > Back-end >  Apply gradient while GlideImage is loading on JetpackCompose
Apply gradient while GlideImage is loading on JetpackCompose

Time:11-26

I want to apply a gradient as the loading state to the GlideImage while the image is loading. How can I do this?

Currently I'm placing a Gradient Box and the image inside, but this doesn't work for images with no background.

My current code is:

Box(
        modifier = Modifier.background(
            brush = Brush.linearGradient(
                listOf(
                    Gray,
                    Color.White
                )
            )
        )
    ) {
        GlideImage(
            model = banner.imageUrl,
            contentDescription = null,
            contentScale = ContentScale.FillHeight,
            modifier = Modifier.coloredShadow(ShadowBannerImage, 0.28f)
        )
    }

For example, this case, it receives a PNG image and, since GlideImage is inside a box with gradient, the gradient will appear behind image, producing a effect that image as background, what is not supposed to happen. The image should only have background while Glide is loading it.

enter image description here

CodePudding user response:

Currently bumptech glide doesn't support placeholders or loading composables.

Similary while Glide’s placeholder, error and fallback request options work and can be provided via GlideImage’s RequestBuilderTransform, we do not currently support custom Composable functions for each of those states.

So I suggest you to use landscapist. And it is signature is like this:

@Composable
public fun GlideImage(
    imageModel: () -> Any?,
    modifier: Modifier = Modifier,
    glideRequestType: GlideRequestType = GlideRequestType.DRAWABLE,
    requestBuilder: @Composable () -> RequestBuilder<*> = {
        LocalGlideProvider.getGlideRequestBuilder()
    },
    requestOptions: @Composable () -> RequestOptions = {
        LocalGlideProvider.getGlideRequestOptions()
    },
    requestListener: (() -> RequestListener<Any>)? = null,
    component: ImageComponent = rememberImageComponent {},
    imageOptions: ImageOptions = ImageOptions(),
    onImageStateChanged: (GlideImageState) -> Unit = {},
    @DrawableRes previewPlaceholder: Int = 0,
    loading: @Composable (BoxScope.(imageState: GlideImageState.Loading) -> Unit)? = null,
    success: @Composable (BoxScope.(imageState: GlideImageState.Success) -> Unit)? = null,
    failure: @Composable (BoxScope.(imageState: GlideImageState.Failure) -> Unit)? = null
)

You can set your gradient composable to loading parameter of GlideImage :

 GlideImage(
    ...
    loading = Box( modifier = Modifier.background(
                        brush = Brush.linearGradient(
                          listOf(Gray, Color.White)
                        ))
                 ) 
 )
  • Related