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{ }
を使用します。この
修飾子はサイズと位置の変更を親に反映させ、
できます。
たとえば、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) ) }
コンポーザブルのパディングをアニメーション化する
コンポーザブルのパディングをアニメーション化するには、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 プロパティを
状態ごとに異なります。
テキストの拡大縮小、移動、回転をアニメーション化する
テキストの縮尺、翻訳、回転をアニメーション化する場合は、textMotion
を設定します。
パラメータを TextStyle
の 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( // ... ) } }
適用される開始遷移と終了遷移にはさまざまな種類があります。 効果の違いについて詳しくは、 ドキュメントをご覧ください。
アニメーションを繰り返す
infiniteRepeatable
で rememberInfiniteTransition
を使用する
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)) }
同時実行アニメーションを作成する
<ph type="x-smartling-placeholder">コルーチン API(Animatable#animateTo()
または animate
)を使用する。または、
Transition
API を使用して、同時アニメーションを実現します。複数の
コルーチンのコンテキストで関数を起動すると、同時にアニメーションが起動されます。
time:
val alphaAnimation = remember { Animatable(0f) } val yAnimation = remember { Animatable(0f) } LaunchedEffect("animationKey") { launch { alphaAnimation.animateTo(1f) } launch { yAnimation.animateTo(100f) } }
updateTransition
API を使用すると、同じ状態を使用して、
多数の異なるプロパティ アニメーションを同時に使用できます。以下の例は、以下のアニメーションの
状態変化によって制御される rect
と borderWidth
の 2 つのプロパティ:
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
: 物理ベースのアニメーション。すべてのアニメーションのデフォルトです。マイページ stiffness または dampingRatio を変更して、異なるアニメーションを作成できます。 カスタマイズすることもできます。tween
(between の略): 時間ベースのアニメーション、アニメーションEasing
関数を使用して 2 つの値の間で分散できます。keyframes
: スコープ内の特定のキーポイントで値を指定するための仕様 作成します。repeatable
: 一定回数実行される期間ベースの仕様。RepeatMode
で指定されます。infiniteRepeatable
: 永続的に実行される期間ベースの仕様。snap
: アニメーションなしで終了値にすばやくスナップします。
AnimationSpecs の詳細については、ドキュメント全文をご覧ください。
参考情報
Compose における楽しいアニメーションのその他の例については、以下をご覧ください。
- Compose の 5 つのクイック アニメーション
- Compose で Jellyfish を動かす
- Compose での
AnimatedContent
のカスタマイズ - Compose で Easing 関数を活用する