Compose でのアニメーションのクイックガイド

Compose には多くの組み込みアニメーション メカニズムがあり、どれを選択すればよいか迷うことがあります。一般的なアニメーションのユースケースを以下に示します。利用可能なさまざまな API オプション の詳細については、Compose アニメーション の完全なドキュメントをご覧ください。

一般的なコンポーザブルのプロパティをアニメーション化する

Compose には、一般的なアニメーションのユースケースの多くを解決できる便利な API が用意されています。このセクションでは、コンポーザブルの一般的なプロパティをアニメーション化する方法について説明します。

表示 / 非表示をアニメーション化する

緑色のコンポーザブルが自身を表示したり非表示にしたりする
図 1.Column 内のアイテムの表示と非表示をアニメーション化する

AnimatedVisibility を使用して、コンポーザブルを非表示または表示します。AnimatedVisibility 内の子は、独自の入退場トランジションに Modifier.animateEnterExit() を使用できます。

var visible by remember {
    mutableStateOf(true)
}
// Animated visibility will eventually remove the item from the composition once the animation has finished.
AnimatedVisibility(visible) {
    // your composable here
    // ...
}

AnimatedVisibility の入退場パラメータを使用すると、コンポーザブルの表示と非表示の動作を構成できます。詳細については、完全な ドキュメントをご覧ください。

コンポーザブルの表示 / 非表示をアニメーション化するもう 1 つの方法は、 アルファを時間経過とともにアニメーション化することです。animateFloatAsState

var visible by remember {
    mutableStateOf(true)
}
val animatedAlpha by animateFloatAsState(
    targetValue = if (visible) 1.0f else 0f,
    label = "alpha"
)
Box(
    modifier = Modifier
        .size(200.dp)
        .graphicsLayer {
            alpha = animatedAlpha
        }
        .clip(RoundedCornerShape(8.dp))
        .background(colorGreen)
        .align(Alignment.TopCenter)
) {
}

ただし、アルファを変更すると、コンポーザブルがコンポジションに残る という注意点があります。コンポーザブルは、レイアウトされたスペースを引き続き占有します。これにより、スクリーン リーダーやその他のユーザー補助メカニズムが、画面上のアイテムを認識し続ける可能性があります。一方、AnimatedVisibility は最終的にコンポジションからアイテムを削除します。

コンポーザブルのアルファ値をアニメーション表示する
図 2.コンポーザブルのアルファをアニメーション化する

背景色をアニメーション化する

アニメーションとして背景色が時間とともに変化するコンポーザブル。色が互いにフェードインします。
図 3.コンポーザブルの背景色をアニメーション化する

val animatedColor by animateColorAsState(
    if (animateBackgroundColor) colorGreen else colorBlue,
    label = "color"
)
Column(
    modifier = Modifier.drawBehind {
        drawRect(animatedColor)
    }
) {
    // your composable here
}

このオプションは、Modifier.background() を使用するよりもパフォーマンスが優れています。 Modifier.background() は 1 回限りの色の設定には適していますが、色を時間経過とともにアニメーション化すると、必要以上に再コンポーズが発生する可能性があります。

背景色を無限にアニメーション化する方法については、アニメーションを繰り返す をご覧ください。

コンポーザブルのサイズをアニメーション化する

サイズ変更をスムーズにアニメーション化する緑色のコンポーザブル。
図 4.コンポーザブルが小さいサイズから大きいサイズにスムーズにアニメーション化する

Compose では、コンポーザブルのサイズをさまざまな方法でアニメーション化できます。コンポーザブルのサイズ変更間のアニメーションには、 animateContentSize() を使用します。

たとえば、1 行から複数行に展開できるテキストを含むボックスがある場合は、Modifier.animateContentSize() を使用してスムーズなトランジションを実現できます。

var expanded by remember { mutableStateOf(false) }
Box(
    modifier = Modifier
        .background(colorBlue)
        .animateContentSize()
        .height(if (expanded) 400.dp else 200.dp)
        .fillMaxWidth()
        .clickable(
            interactionSource = remember { MutableInteractionSource() },
            indication = null
        ) {
            expanded = !expanded
        }

) {
}

AnimatedContent を使用して、SizeTransform でサイズ変更の方法を記述することもできます。

コンポーザブルの位置をアニメーション化する

緑色のコンポーザブルが右下にスムーズにアニメーション表示されている
図 5.オフセットで移動するコンポーザブル

コンポーザブルの位置をアニメーション化するには、Modifier.offset{ }animateIntOffsetAsState() を組み合わせます。

var moved by remember { mutableStateOf(false) }
val pxToMove = with(LocalDensity.current) {
    100.dp.toPx().roundToInt()
}
val offset by animateIntOffsetAsState(
    targetValue = if (moved) {
        IntOffset(pxToMove, pxToMove)
    } else {
        IntOffset.Zero
    },
    label = "offset"
)

Box(
    modifier = Modifier
        .offset {
            offset
        }
        .background(colorBlue)
        .size(100.dp)
        .clickable(
            interactionSource = remember { MutableInteractionSource() },
            indication = null
        ) {
            moved = !moved
        }
)

位置やサイズをアニメーション化するときに、コンポーザブルが他のコンポーザブルの上または下に描画されないようにするには、Modifier.layout{ } を使用します。この修飾子は、サイズと位置の変更を親に伝播し、親は他の子に影響を与えます。

たとえば、Column 内で Box を移動し、Box の移動時に他の子を移動する必要がある場合は、次のように Modifier.layout{ } でオフセット情報を含めます。

var toggled by remember {
    mutableStateOf(false)
}
val interactionSource = remember {
    MutableInteractionSource()
}
Column(
    modifier = Modifier
        .padding(16.dp)
        .fillMaxSize()
        .clickable(indication = null, interactionSource = interactionSource) {
            toggled = !toggled
        }
) {
    val offsetTarget = if (toggled) {
        IntOffset(150, 150)
    } else {
        IntOffset.Zero
    }
    val offset = animateIntOffsetAsState(
        targetValue = offsetTarget, label = "offset"
    )
    Box(
        modifier = Modifier
            .size(100.dp)
            .background(colorBlue)
    )
    Box(
        modifier = Modifier
            .layout { measurable, constraints ->
                val offsetValue = if (isLookingAhead) offsetTarget else offset.value
                val placeable = measurable.measure(constraints)
                layout(placeable.width + offsetValue.x, placeable.height + offsetValue.y) {
                    placeable.placeRelative(offsetValue)
                }
            }
            .size(100.dp)
            .background(colorGreen)
    )
    Box(
        modifier = Modifier
            .size(100.dp)
            .background(colorBlue)
    )
}

2 つのボックスがあり、2 つ目のボックスの X 座標と Y 座標がアニメーション化され、3 つ目のボックスが Y の量だけ移動することで応答しています。
図 6.Modifier.layout{ }
を使用してアニメーション化する

コンポーザブルのパディングをアニメーション化する

クリックすると緑色のコンポーザブルが拡大縮小し、パディングがアニメーション表示される
図 7.パディングがアニメーション化されたコンポーザブル

コンポーザブルのパディングをアニメーション化するには、animateDpAsStateModifier.padding() を組み合わせます。

var toggled by remember {
    mutableStateOf(false)
}
val animatedPadding by animateDpAsState(
    if (toggled) {
        0.dp
    } else {
        20.dp
    },
    label = "padding"
)
Box(
    modifier = Modifier
        .aspectRatio(1f)
        .fillMaxSize()
        .padding(animatedPadding)
        .background(Color(0xff53D9A1))
        .clickable(
            interactionSource = remember { MutableInteractionSource() },
            indication = null
        ) {
            toggled = !toggled
        }
)

コンポーザブルの標高をアニメーション化する

図 8. クリック時にコンポーザブルの標高がアニメーション化する

コンポーザブルの標高をアニメーション化するには、animateDpAsStateModifier.graphicsLayer{ } を組み合わせます。1 回限りの標高の変更には、Modifier.shadow() を使用します。シャドウをアニメーション化する場合は、Modifier.graphicsLayer{ } 修飾子を使用する方がパフォーマンスが優れています。

val mutableInteractionSource = remember {
    MutableInteractionSource()
}
val pressed = mutableInteractionSource.collectIsPressedAsState()
val elevation = animateDpAsState(
    targetValue = if (pressed.value) {
        32.dp
    } else {
        8.dp
    },
    label = "elevation"
)
Box(
    modifier = Modifier
        .size(100.dp)
        .align(Alignment.Center)
        .graphicsLayer {
            this.shadowElevation = elevation.value.toPx()
        }
        .clickable(interactionSource = mutableInteractionSource, indication = null) {
        }
        .background(colorGreen)
) {
}

または、Card コンポーザブルを使用して、標高プロパティに 異なる値を設定します。

テキストのスケール、変換、回転をアニメーション化する

「Hello」と表示されたテキスト コンポーザブルが、小さいサイズと大きいサイズの間でアニメーション表示されている。
図 9.2 つのサイズ間でスムーズにアニメーション化するテキスト

テキストのスケール、変換、回転をアニメーション化する場合は、textMotion パラメータをTextStyleTextMotion.Animated設定します。これにより、テキスト アニメーション間のトランジションがスムーズになります。Modifier.graphicsLayer{ } を使用して、テキストを変換、回転、スケーリングします。

val infiniteTransition = rememberInfiniteTransition(label = "infinite transition")
val scale by infiniteTransition.animateFloat(
    initialValue = 1f,
    targetValue = 8f,
    animationSpec = infiniteRepeatable(tween(1000), RepeatMode.Reverse),
    label = "scale"
)
Box(modifier = Modifier.fillMaxSize()) {
    Text(
        text = "Hello",
        modifier = Modifier
            .graphicsLayer {
                scaleX = scale
                scaleY = scale
                transformOrigin = TransformOrigin.Center
            }
            .align(Alignment.Center),
        // Text composable does not take TextMotion as a parameter.
        // Provide it via style argument but make sure that we are copying from current theme
        style = LocalTextStyle.current.copy(textMotion = TextMotion.Animated)
    )
}

テキストの色をアニメーション化する

「Hello Compose」という語句の色が緑と青の間でアニメーション表示されている
図 10.テキストの色をアニメーション化する例

テキストの色をアニメーション化するには、BasicText コンポーザブルで color ラムダを使用します。

val infiniteTransition = rememberInfiniteTransition(label = "infinite transition")
val animatedColor by infiniteTransition.animateColor(
    initialValue = Color(0xFF60DDAD),
    targetValue = Color(0xFF4285F4),
    animationSpec = infiniteRepeatable(tween(1000), RepeatMode.Reverse),
    label = "color"
)

BasicText(
    text = "Hello Compose",
    color = {
        animatedColor
    },
    // ...
)

さまざまな種類のコンテンツを切り替える

「読み込み中」と表示された緑色の画面、「読み込み完了」と表示された青色の画面、「エラー」と表示された白色の画面が、シンプルなアニメーションで切り替わっている。
図 11.AnimatedContent を使用して、さまざまなコンポーザブル間の変更をアニメーション化する(速度を遅くする)

AnimatedContent を使用してさまざまなコンポーザブル間をアニメーション化します。コンポーザブル間の標準的なフェードが必要な場合は、Crossfade を使用します。

var state by remember {
    mutableStateOf(UiState.Loading)
}
AnimatedContent(
    state,
    transitionSpec = {
        fadeIn(
            animationSpec = tween(3000)
        ) togetherWith fadeOut(animationSpec = tween(3000))
    },
    modifier = Modifier.clickable(
        interactionSource = remember { MutableInteractionSource() },
        indication = null
    ) {
        state = when (state) {
            UiState.Loading -> UiState.Loaded
            UiState.Loaded -> UiState.Error
            UiState.Error -> UiState.Loading
        }
    },
    label = "Animated Content"
) { targetState ->
    when (targetState) {
        UiState.Loading -> {
            LoadingScreen()
        }
        UiState.Loaded -> {
            LoadedScreen()
        }
        UiState.Error -> {
            ErrorScreen()
        }
    }
}

AnimatedContent は、さまざまな種類の入退場トランジションを表示するようにカスタマイズできます。詳細については、 AnimatedContent のドキュメントまたは ブログ投稿 AnimatedContent に関するこちらのをご覧ください。

さまざまなデスティネーションに移動しながらアニメーション化する

2 つのコンポーザブル(1 つは緑色で「Landing」、もう 1 つは青色で「Detail」と表示)。詳細コンポーザブルをランディング コンポーザブルの上にスライドさせてアニメーション表示しています。
図 12.navigation-compose を使用してコンポーザブル間をアニメーション化する

navigation-compose アーティファクトを使用するときに、コンポーザブル間のトランジションをアニメーション化するには、コンポーザブルで enterTransitionexitTransition を指定します。最上位の NavHost で、すべてのデスティネーションに使用するデフォルトのアニメーションを設定することもできます。

val navController = rememberNavController()
NavHost(
    navController = navController, startDestination = "landing",
    enterTransition = { EnterTransition.None },
    exitTransition = { ExitTransition.None }
) {
    composable("landing") {
        ScreenLanding(
            // ...
        )
    }
    composable(
        "detail/{photoUrl}",
        arguments = listOf(navArgument("photoUrl") { type = NavType.StringType }),
        enterTransition = {
            fadeIn(
                animationSpec = tween(
                    300, easing = LinearEasing
                )
            ) + slideIntoContainer(
                animationSpec = tween(300, easing = EaseIn),
                towards = AnimatedContentTransitionScope.SlideDirection.Start
            )
        },
        exitTransition = {
            fadeOut(
                animationSpec = tween(
                    300, easing = LinearEasing
                )
            ) + slideOutOfContainer(
                animationSpec = tween(300, easing = EaseOut),
                towards = AnimatedContentTransitionScope.SlideDirection.End
            )
        }
    ) { backStackEntry ->
        ScreenDetails(
            // ...
        )
    }
}

入退場トランジションにはさまざまな種類があり、入退場するコンテンツにさまざまな効果を適用できます。詳細については、 ドキュメントをご覧ください。

アニメーションを繰り返す

緑色の背景が青色の背景に変化し、2 色の間でアニメーションが無限に繰り返されます。
図 13.2 つの値の間で無限にアニメーション化する背景色

rememberInfiniteTransitioninfiniteRepeatable animationSpec を使用して、アニメーションを連続して繰り返します。RepeatModes を変更して、往復の方法を指定します。

repeatable を使用して、指定した回数だけ繰り返します。

val infiniteTransition = rememberInfiniteTransition(label = "infinite")
val color by infiniteTransition.animateColor(
    initialValue = Color.Green,
    targetValue = Color.Blue,
    animationSpec = infiniteRepeatable(
        animation = tween(1000, easing = LinearEasing),
        repeatMode = RepeatMode.Reverse
    ),
    label = "color"
)
Column(
    modifier = Modifier.drawBehind {
        drawRect(color)
    }
) {
    // your composable here
}

コンポーザブルの起動時にアニメーションを開始する

LaunchedEffect は、コンポーザブルがコンポジションに入ると実行されます。コンポーザブルの起動時にアニメーションを開始します。これを使用して、アニメーションの状態変更を制御できます。AnimatableanimateTo メソッドを使用して、起動時にアニメーションを開始します。

val alphaAnimation = remember {
    Animatable(0f)
}
LaunchedEffect(Unit) {
    alphaAnimation.animateTo(1f)
}
Box(
    modifier = Modifier.graphicsLayer {
        alpha = alphaAnimation.value
    }
)

シーケンシャル アニメーションを作成する

4 つの円の間を緑色の矢印がアニメーションで移動し、1 つずつ順番にアニメーション化されている。
図 14.シーケンシャル アニメーションが 1 つずつ進行する様子を示す図。

Animatable コルーチン API を使用して、順次アニメーションまたは同時実行アニメーションを実行します。AnimatableanimateTo を連続して呼び出すと、各アニメーションは前のアニメーションが完了するまで待機してから処理を進めます。これは、中断関数であるためです。

val alphaAnimation = remember { Animatable(0f) }
val yAnimation = remember { Animatable(0f) }

LaunchedEffect("animationKey") {
    alphaAnimation.animateTo(1f)
    yAnimation.animateTo(100f)
    yAnimation.animateTo(500f, animationSpec = tween(100))
}

並行アニメーションを作成する

3 つの円があり、それぞれに緑色の矢印がアニメーションで表示され、同時にすべてがアニメーションで表示される。
図 15.並行アニメーションが同時に進行する様子を示す図。

並行アニメーションを実現するには、コルーチン API(Animatable#animateTo() または animate)または Transition API を使用します。コルーチン コンテキストで複数の起動関数を使用すると、アニメーションが同時に起動します。

val alphaAnimation = remember { Animatable(0f) }
val yAnimation = remember { Animatable(0f) }

LaunchedEffect("animationKey") {
    launch {
        alphaAnimation.animateTo(1f)
    }
    launch {
        yAnimation.animateTo(100f)
    }
}

updateTransition API を使用すると、同じ状態を使用して さまざまなプロパティ アニメーションを同時に制御できます。次の例では、状態の変更によって制御される 2 つのプロパティ(rectborderWidth)をアニメーション化します。

var currentState by remember { mutableStateOf(BoxState.Collapsed) }
val transition = updateTransition(currentState, label = "transition")

val rect by transition.animateRect(label = "rect") { state ->
    when (state) {
        BoxState.Collapsed -> Rect(0f, 0f, 100f, 100f)
        BoxState.Expanded -> Rect(100f, 100f, 300f, 300f)
    }
}
val borderWidth by transition.animateDp(label = "borderWidth") { state ->
    when (state) {
        BoxState.Collapsed -> 1.dp
        BoxState.Expanded -> 0.dp
    }
}

アニメーションのパフォーマンスを最適化する

Compose のアニメーションは、パフォーマンスの問題を引き起こす可能性があります。これは、アニメーションの性質によるものです。アニメーションは、画面上のピクセルをフレームごとにすばやく移動または変更して、動きの錯覚を生み出します。

Compose のさまざまなフェーズ(コンポジション、レイアウト、描画)について考えてみましょう。アニメーションによってレイアウト フェーズが変更される場合は、影響を受けるすべてのコンポーザブルを再レイアウトして再描画する必要があります。アニメーションが描画フェーズで発生する場合、レイアウト フェーズでアニメーションを実行するよりもパフォーマンスが優れています。これは、全体的な処理量が少なくなるためです。

アニメーション化中にアプリの処理をできるだけ少なくするには、可能な限り Modifier のラムダ バージョンを選択します。これにより、再コンポーズがスキップされ、コンポジション フェーズの外でアニメーションが実行されます。それ以外の場合は、Modifier.graphicsLayer{ } を使用します。この修飾子は常に描画フェーズで実行されます。詳細については、パフォーマンスに関するドキュメントの読み取りの遅延をご覧ください。

アニメーションのタイミングを変更する

Compose では、ほとんどのアニメーションにデフォルトでスプリング アニメーションが使用されます。スプリング アニメーション(物理ベースのアニメーション)は、より自然な動きになります。また、固定時間ではなくオブジェクトの現在の速度を考慮するため、中断可能です。 デフォルトをオーバーライドする場合は、前述のアニメーション API を使用して animationSpec を設定し、アニメーションの実行方法をカスタマイズできます。たとえば、特定の間隔で実行するか、より弾むようにするかなどです。

さまざまな animationSpec オプションの概要を以下に示します。

  • spring: 物理ベースのアニメーション。すべてのアニメーションのデフォルトです。硬さや減衰比を変更して、アニメーションのルック&フィールを変更できます。
  • tween の略): 時間ベースのアニメーション。Easing 関数を使用して 2 つの値の間をアニメーション化します。
  • keyframes: アニメーションの特定のキーポイントで値を指定するための仕様。
  • repeatable: RepeatMode で指定された回数だけ実行される時間ベースの仕様。
  • infiniteRepeatable: 無限に実行される時間ベースの仕様。
  • snap: アニメーションなしで終了値に瞬時にスナップします。
仕様セットなしの場合とカスタムの Spring 仕様セットの場合を示す 2 つのアニメーション。
図 16.仕様が設定されていない場合とカスタム スプリング仕様が設定されている場合

animationSpec の詳細については、完全なドキュメントをご覧ください。

参考情報

Compose の楽しいアニメーションの例については、以下をご覧ください。