常见共享元素用例

为共享元素添加动画效果时,有一些特定用例具有特定的建议。

异步图片

通常使用库异步加载图片,例如在使用 Coil 的 AsyncImage 可组合项时。为了在两个可组合项之间无缝工作,建议将 placeholderMemoryCacheKey()memoryCacheKey() 设置为与派生自共享元素键的字符串相同的键,这样匹配的共享元素的缓存键就相同。新的共享元素会将其匹配项的缓存用作占位符,直到加载新图片。

AsyncImage 的典型用法如下:

AsyncImage(
    model = ImageRequest.Builder(LocalContext.current)
        .data("your-image-url")
        .crossfade(true)
        .placeholderMemoryCacheKey("image-key") //  same key as shared element key
        .memoryCacheKey("image-key") // same key as shared element key
        .build(),
    placeholder = null,
    contentDescription = null,
    modifier = Modifier
        .size(120.dp)
        .sharedBounds(
            rememberSharedContentState(
                key = "image-key"
            ),
            animatedVisibilityScope = this
        )
)

文本

如需为 fontSize 更改添加动画效果,请使用 Modifier.sharedBounds()resizeMode = ScaleToBounds()。这种过渡会使大小变化相对流畅。您可以调整 contentScale 参数,为特定字体粗细或样式添加动画效果。

Text(
    text = "This is an example of how to share text",
    modifier = Modifier
        .wrapContentWidth()
        .sharedBounds(
            rememberSharedContentState(
                key = "shared Text"
            ),
            animatedVisibilityScope = this,
            enter = fadeIn(),
            exit = fadeOut(),
            resizeMode = SharedTransitionScope.ResizeMode.ScaleToBounds()
        )
)

默认情况下,TextAlign 更改不是以动画形式呈现。相反,应使用 Modifier.wrapContentSize() / Modifier.wrapContentWidth(),而不是为共享转换使用不同的 TextAlign