使用图片加载库显示动态 GIF
动态 GIF 可以增强沟通和自我表达,为对话增添活力与趣味。与纯静态图片或文本相比,它们能更有效地传达情绪、反应和幽默感。GIF 在网络文化中的流行,使其成为现代功能和丰富多媒体体验中不可或缺的一部分,能帮助应用保持吸引力并满足用户期望。
使用图片加载库显示动态 GIF
图片加载库可以为你完成大部分繁重的工作,通常还会针对动态 GIF 等功能添加向后兼容支持。以下代码展示了如何使用 Coil 图片加载库实现动态 GIF 播放:
添加 Coil 的 GIF 依赖项
implementation("io.coil-kt:coil-gif:2.6.0")
创建支持 GIF 的加载器,同时使用 Android 9(API 级别 28)中添加的平台 ImageDecoder,以及 Coil 的 GifDecoder 以实现向后兼容。
val gifEnabledLoader = ImageLoader.Builder(this)
.components {
if ( SDK_INT >= 28 ) {
add(ImageDecoderDecoder.Factory())
} else {
add(GifDecoder.Factory())
}
}.build()
在 Coil 的 AsyncImage 可组合项中使用 gifEnabledLoader
AsyncImage(
imageLoader = gifEnabledLoader,
...
)
使用 Android 平台支持显示动态 GIF
AsyncImage(
model = request,
imageLoader = videoEnabledLoader,
contentDescription = null
)
Android 9+(API 级别 28)内置了对动态 GIF 文件的支持。在 Accompanist 库的辅助下,Jetpack Compose 只需几行代码即可播放这些动画。
添加 Accompanist 库依赖以支持 drawable painter
implementation("com.google.accompanist:accompanist-drawablepainter:0.35.0-alpha")
创建一种方法,利用 ImageDecoder 将动态 GIF 加载到 AnimatedImageDrawable 中
private fun createAnimatedImageDrawableFromImageDecoder(context: Context, uri: Uri): AnimatedImageDrawable {
val source = ImageDecoder.createSource(context.contentResolver, uri)
val drawable = ImageDecoder.decodeDrawable(source)
return drawable as AnimatedImageDrawable
}
将 rememberDrawablePainter 与 AnimatedImageDrawable 结合使用
Image(
painter = rememberDrawablePainter(
drawable = createAnimatedImageDrawableFromImageDecoder(applicationContext, mediaUri)),
contentDescription = "animated gif"
)
支持来自图片键盘和其他富媒体内容的 GIF 文件
动态 GIF 文件是许多 Android 键盘(包括 Google 的 Gboard)中的热门功能。目前,支持任何类型的贴纸或动画(无论是来自输入法还是其他应用)的推荐方式是使用 OnReceiveContentListener。
请参阅接收富媒体内容,了解有关如何在应用中实现接收 GIF 动画和其他富媒体内容支持的更多信息。
