常见共享元素用例

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

异步图片

常见做法是使用库异步加载图片,例如在使用 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