Hey guys, I’m using the new animatedImage Composab...
# compose-desktop
l
Hey guys, I’m using the new animatedImage Composable to play GIFs, but it plays GIFs infinitely as a default behavior. Is there any way to play the GIFs just once?
Copy code
loadOrNull { loadResourceAnimatedImage(path) }?.animate() ?: ImageBitmap.Blank
Copy code
@Composable
actual fun AnimatedImage.animate(): ImageBitmap {
    when (codec.frameCount) {
        0 -> return ImageBitmap.Blank // No frames at all
        1 -> {
            // Just one frame, no animation
            val bitmap = remember(codec) { Bitmap().apply { allocPixels(codec.imageInfo) } }
            remember(bitmap) {
                codec.readPixels(bitmap, 0)
            }
            return bitmap.asComposeImageBitmap()
        }
        else -> {
            val transition = rememberInfiniteTransition()
            val frameIndex by transition.animateValue(
                initialValue = 0,
                targetValue = codec.frameCount - 1,
                Int.VectorConverter,
                animationSpec = infiniteRepeatable(
                    animation = keyframes {
                        durationMillis = 0
                        for ((index, frame) in codec.framesInfo.withIndex()) {
                            index at durationMillis
                            val frameDuration = calcFrameDuration(frame)

                            durationMillis += frameDuration
                        }
                    }
                )
            )

            val bitmap = remember(codec) { Bitmap().apply { allocPixels(codec.imageInfo) } }

            remember(bitmap, frameIndex) {
                codec.readPixels(bitmap, frameIndex)
            }

            return bitmap.asComposeImageBitmap()
        }
    }
}