Compose には多くの組み込みアニメーション メカニズムがあり、どれを選択すべきかわからず戸惑うかもしれません。アニメーションの一般的なユースケースは次のとおりです。利用可能なさまざまな API オプションの詳細については、Compose アニメーションのドキュメントをご覧ください。
共通のコンポーザブル プロパティをアニメーション化する
Compose には、多くの一般的なアニメーションのユースケースを解決できる便利な API が用意されています。このセクションでは、コンポーザブルの共通プロパティをアニメーション化する方法について説明します。
表示 / 非表示のアニメーション
コンポーザブルの表示と非表示を切り替えるには、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
は最終的にコンポジションからアイテムを削除します。
背景色をアニメーション化する
val animatedColor by animateColorAsState( if (animateBackgroundColor) colorGreen else colorBlue, label = "color" ) Column( modifier = Modifier.drawBehind { drawRect(animatedColor) } ) { // your composable here }
このオプションは、Modifier.background()
を使用するよりもパフォーマンスが高くなります。Modifier.background()
はワンショット カラー設定には使用できますが、時間の経過とともに色をアニメーション化すると、必要以上に多くの再コンポジションが発生する可能性があります。
背景色を無限にアニメーション化する方法については、アニメーションを繰り返すをご覧ください。
コンポーザブルのサイズをアニメーション化する
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
を使用して、サイズ変更方法を記述することもできます。
コンポーザブルの位置をアニメーション化する
コンポーザブルの位置をアニメーション化するには、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{ }
を使用します。この修飾子は、サイズと位置の変更を親に反映し、他の子に影響を与えます。
たとえば、Box
を Column
内で移動し、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) ) }
コンポーザブルのパディングをアニメーション化する
コンポーザブルのパディングをアニメーション化するには、animateDpAsState
と Modifier.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 } )
コンポーザブルのエレベーションをアニメーション化する
コンポーザブルのエレベーションをアニメーション化するには、animateDpAsState
を Modifier.graphicsLayer{ }
と組み合わせて使用します。高度を一度だけ変更するには、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
コンポーザブルを使用して、Elevation プロパティを状態ごとに異なる値に設定します。
テキストのスケール、平行移動、回転をアニメーション化する
テキストのスケーリング、移動、回転をアニメーション化する場合は、TextStyle
の textMotion
パラメータを TextMotion.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) ) }
アニメーションのテキストの色
テキストの色をアニメーション化するには、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 }, // ... )
コンテンツの種類を切り替える
異なるコンポーザブル間をアニメーション化するには、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
に関するブログ投稿をご覧ください。
さまざまなデスティネーションへの移動中にアニメーション表示する
navigation-compose アーティファクトを使用している場合にコンポーザブル間の遷移をアニメーション化するには、コンポーザブルに enterTransition
と exitTransition
を指定します。最上位の 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( // ... ) } }
開始と終了の遷移にはさまざまな種類があり、受信コンテンツと送信コンテンツに異なる効果が適用されます。詳しくは、ドキュメントをご覧ください。
アニメーションを繰り返す
rememberInfiniteTransition
と infiniteRepeatable
animationSpec
を使用して、アニメーションを継続的に繰り返します。RepeatModes
を変更して、やり取りの方法を指定します。
finiteRepeatable
を使用して、指定した回数を繰り返す
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
は、コンポーザブルがコンポジションに入ると実行されます。コンポーザブルの起動時にアニメーションを開始します。これを使用して、アニメーション状態の変更を促進できます。animateTo
メソッドとともに Animatable
を使用して、起動時にアニメーションを開始します。
val alphaAnimation = remember { Animatable(0f) } LaunchedEffect(Unit) { alphaAnimation.animateTo(1f) } Box( modifier = Modifier.graphicsLayer { alpha = alphaAnimation.value } )
連続したアニメーションを作成する
Animatable
コルーチン API を使用して、順次アニメーションまたは同時実行アニメーションを実行します。Animatable
で animateTo
を順番に呼び出すと、各アニメーションは前のアニメーションが終了するまで待ってから次に進みます。これは suspend 関数であるためです。
val alphaAnimation = remember { Animatable(0f) } val yAnimation = remember { Animatable(0f) } LaunchedEffect("animationKey") { alphaAnimation.animateTo(1f) yAnimation.animateTo(100f) yAnimation.animateTo(500f, animationSpec = tween(100)) }
同時実行アニメーションを作成する
コルーチン 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 つのプロパティ rect
と borderWidth
をアニメーション化しています。
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 のデフォルトでは、ほとんどのアニメーションに spring アニメーションが使用されます。ばね、つまり物理ベースのアニメーションは、より自然に感じられます。また、固定時間ではなく、オブジェクトの現在の速度が考慮されるため、割り込み可能です。デフォルトをオーバーライドする場合、上記で説明したすべてのアニメーション API で animationSpec
を設定して、特定の時間にわたって実行したい、あるいは弾力を高めるようにアニメーションの実行方法をカスタマイズできます。
さまざまな animationSpec
オプションの概要を以下に示します。
spring
: 物理ベースのアニメーション。すべてのアニメーションのデフォルトです。剛性または dampingRatio を変更して、異なるアニメーションの外観にすることができます。tween
(Between): 時間ベースのアニメーション。Easing
関数を使用して 2 つの値の間でアニメーション化します。keyframes
: アニメーションの特定のキーポイントで値を指定するための仕様です。repeatable
:RepeatMode
で指定された回数を実行する期間ベースの仕様。infiniteRepeatable
: 永続的に実行される期間ベースの仕様。snap
: アニメーションなしで、すぐに終了値にスナップします。
animationSpecs の詳細については、ドキュメント全文をご覧ください。
参考情報
Compose の楽しいアニメーションの例については、以下をご覧ください。
- Compose の 5 つのクイック アニメーション
- Compose で Jellyfish を動かす
- Compose での
AnimatedContent
のカスタマイズ - Compose のイージング関数へのイージング