Coil: Resize images wider than the device using a scale factor

Created on 11 Aug 2020  路  2Comments  路  Source: coil-kt/coil

Hi!
Thanks for the great library.

I am looking for a way to resize only those images wider than the device width using a scalar factor given by:

 val factor = if (sourceWidth > maxWidth) {
                maxWidth.toFloat() / sourceWidth
            } else 1f

Where maxWidth is the device's width

I was able to successfully do this using a transformation:

class MaxWidthTransformation(private val maxWidth: Int) : Transformation {

        override fun key(): String = "DensityTransformation"

        override suspend fun transform(pool: BitmapPool, input: Bitmap, size: Size): Bitmap {
            val sourceWidth = input.width
            val factor = if (sourceWidth > maxWidth) {
                maxWidth.toFloat() / sourceWidth
            } else 1f
            val finalWidth = sourceWidth * factor
            val finalHeight = input.height * factor

            val config = if (input.config != null) input.config else Bitmap.Config.ARGB_8888
            val output = pool.get(finalWidth.toInt(), finalHeight.toInt(), config)
            output.setHasAlpha(true)

            val targetRect = RectF(0f, 0f, finalWidth, finalHeight)

            val canvas = Canvas(output)
            canvas.drawBitmap(input, null, targetRect, null)
            pool.put(input)

            return output
        }

    }

But this breaks Animated drawables.

I am using a custom target as images are rendered in a drawable, not in an ImageView.

This LoadRequest configuration almost do the trick but wider images are not entirely centered:

  LoadRequest.Builder(context)
                .data(sourceUrl)
                .scale(FIT)
                .crossfade(true)
                .target(AnimatableTarget(view, levelListDrawable))
                .build()

Any advice?

Thanks!

question

All 2 comments

I think you can accomplish this use case by setting size(maxWidth, Int.MAX_VALUE).scale(Scale.FIT).precision(Precision.INEXACT) on your request. That will load the image so its width is at most maxWidth while not necessarily upscaling that image to meet that maxWidth.

Transformations only work for static images which is why your solution won't work for animated images.

That worked! Thanks!

Was this page helpful?
0 / 5 - 0 ratings