显示动画 GIF

动画 GIF 增强了交流和自我表达,为对话增添了动态且引人入胜的元素,让用户比单独使用静态图片或文本更有效地传达情感、反应和幽默。GIF 在在线文化中的流行使得将其集成到应用中变得至关重要,从而保持相关性并吸引那些期待现代功能和丰富的多媒体体验的用户。

使用图片加载库显示动画 GIF

图片加载库为您做了大量繁重的工作,通常会为动画 GIF 等功能添加向后兼容的支持。以下代码演示了如何使用 Coil 图片加载库 实现动画 GIF 播放

添加用于 GIF 的 Coil 依赖项

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")

创建一个将动画 GIF 加载到 AnimatedImageDrawable 中的方法,使用 ImageDecoder

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 动画及其他富媒体的支持。