在为共享元素添加动画效果时,有一些特定的使用情形有具体的建议。
异步图片
通常会使用库来异步加载图片,例如使用 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
。