共有要素の一般的なユースケース

共有要素をアニメーション化する場合、いくつかの特定のユースケースで具体的な推奨事項があります。

非同期イメージ

一般的には、Coil の AsyncImage コンポーザブルを使用する場合など、ライブラリを使用して画像を非同期で読み込みます。2 つのコンポーザブル間でシームレスに動作するには、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 の変更は、デフォルトではアニメーション化されません。共有遷移には別の TextAlign ではなく、Modifier.wrapContentSize() / Modifier.wrapContentWidth() を使用してください。