Victoria Olegovna
Victoria Olegovna

Reputation: 21

How to use GIF images in Compose Multiplatform?

I'm trying to create a Compose Multiplatform application for Android and iOS. At the moment I am faced with the problem of adding GIFs or lottie animations, because Compose itself does not support adding GIFs and there are no libraries that could help with adding GIFs.

Does anyone know how to solve the problem?

Upvotes: 1

Views: 1285

Answers (1)

Mahozad
Mahozad

Reputation: 24622

Using Kamel library (has some problems)

Version 1.0.0-beta.5 of the multiplatform Kamel library has added experimental support for GIF.

Implementing for each target

Tested with Compose Multiplatform 1.6.11

build.gradle(.kts)

val desktopMain by getting {
    dependencies {
        @OptIn(ExperimentalComposeLibrary::class)
        implementation(compose.desktop.components.animatedImage)
        implementation(compose.desktop.currentOs)
        // ...
    }
}
val androidMain by getting {
    dependencies {
        implementation("io.coil-kt:coil-compose:2.1.0")
        implementation("io.coil-kt:coil-gif:2.1.0")
        // ...
    }
}
Desktop (put your gif file in src/desktopMain/resources/):
@Composable
fun GifImage(fileName: String) {
    var gif by remember { mutableStateOf<AnimatedImage?>(null) }
    LaunchedEffect(Unit) { gif = loadResourceAnimatedImage("image.gif") }
    gif?.let {
        Image(
            bitmap = it.animate(),
            contentDescription = null
        )
    }
    // If your Gif is a non-animated still image, simply use the painterResource
    // Image(painter = painterResource("/$fileName"), contentDescription = null)
}
GifImage("myImage.gif")
Android (put your gif file in drawable/ directory) (thanks goes to this answer):
@Composable
fun GifImage(fileId: Int) {
    val context = LocalContext.current
    val imageLoader = ImageLoader.Builder(context)
        .components {
            if (SDK_INT >= 28) {
                add(ImageDecoderDecoder.Factory())
            } else {
                add(GifDecoder.Factory())
            }
        }
        .build()
    Image(
        painter = rememberAsyncImagePainter(
            ImageRequest.Builder(context).data(data = fileId).apply(block = {
                size(Size.ORIGINAL)
            }).build(), imageLoader = imageLoader
        ),
        contentDescription = null
    )
}
GifImage(R.drawable.YOUR_GIF_NAME)
iOS: See the solution in this discussion

Full code for iOS is available here.

Upvotes: 0

Related Questions