共用元素的常見用途

在製作共用元素動畫時,有些特定用途有專屬建議。

非同步圖片

通常會使用程式庫非同步載入圖片,例如使用 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