Hi! I’m using coil to load images in compose and I...
# compose
i
Hi! I’m using coil to load images in compose and I need to send as a query-param with the width of the composable. Right now the only way I’ve found is using
onGloballyPositioned
on the
Image
modifier to get the size and then set a global variable of an Interceptor.. What I have is something like:
Copy code
Image(
    painter = painter,
    modifier = modifier.onGloballyPositioned {
        coilInterceptor.config.params[PARAM_WIDTH] = it.size.width.toString() 
    },
coilInterceptor is a singleton Interceptor…. I’m trying to avoid this. I much rather prefer passing to the
ImageRequest
directly the url with the size concatenated
z
You should use
onSizeChanged
instead of
onGloballyPositioned
– size has nothing to do with postioin
a
There is already a
size
property in Coil's Interceptor.Chain interface so you shouldn't need to get the size here.
i
okay, yes I’ve seen the
size
method for the ImageRequest. It can receive a
SizeResolver
interface but how do I get the width then? and more importantly how do I “append” this “info” (width) to the url? via an Interceptor or directly concatenating the result to the base url?
Copy code
val painter = rememberAsyncImagePainter(
    model = ImageRequest.Builder(LocalContext.current)
        .size(SizeResolver {
            // add to url?????
            Size(??, ??)
        })
        .data(url)
        .build(),
    contentScale = contentScale,
    imageLoader = context.imageLoader
)
I’m guessing this is what @Albert Chang is mentioning
a
No. I mean you can already access the target size of the image in your
Interceptor
.
Something like
Copy code
class AddWidthParamInterceptor : Interceptor {
    override suspend fun intercept(chain: Interceptor.Chain): ImageResult {
        val request = chain.request
        val width = chain.size.width
        val newRequest = if (width is Dimension.Pixels) {
            val newUri = Uri.parse(request.data as String)
                .buildUpon()
                .appendQueryParameter("width", width.px.toString())
                .build()
            request.newBuilder()
                .data(newUri)
                .build()
        } else {
            request
        }
        return chain.proceed(newRequest)
    }
}

// Then add it to your image loader
ImageLoader.Builder(context)
    .components {
        add(AddWidthParamInterceptor())
    }
    .interceptorDispatcher(<http://Dispatchers.IO|Dispatchers.IO>)
    .build()
i
wow! this is awesome! I didn’t know we had this information at that point! thanks for the trick
560 Views