我正在尝试为 Android 和 iOS 创建一个 Compose 多平台应用程序。目前我面临着添加 GIF 或 lotie 动画的问题,因为 Compose 本身不支持添加 GIF,并且没有可以帮助添加 GIF 的库。
有谁知道如何解决这个问题吗?
Kamel 库
的版本
1.0.0-beta.5
添加了对 GIF 的实验性支持。
已使用 Compose Multiplatform 1.6.11 进行测试
构建.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")
// ...
}
}
src/desktopMain/resources/
):@Composable
fun GifImage(fileName: String) {
var gif by remember { mutableStateOf<AnimatedImage?>(null) }
LaunchedEffect(Unit) {
var path = Path("")
javaClass.getResourceAsStream("/$fileName")?.use { input ->
path = createTempDirectory().resolve(fileName)
path.outputStream().use(input::copyTo)
}
gif = loadAnimatedImage(path.absolutePathString())
}
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")
@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)