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
的輸入和結束參數,您可以設定可組合項在顯示與消失時的行為。詳情請參閱完整說明文件。
另一個為可組合項的顯示設定動畫效果的方法,是使用 animateFloatAsState
隨時間讓 Alpha 動畫呈現動畫效果:
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) ) { }
然而,變更 Alpha 時,必須注意可組合項仍保留在組合中,並持續佔用其所在空間。這可能會導致螢幕閱讀器和其他無障礙機制仍會考慮畫面上的項目。另一方面,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()
。
舉例來說,如果您有一個方塊包含可從一行展開到多行文字的方塊,您可以使用 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
可組合項,將高度屬性設為每個狀態的不同值。
以動畫呈現文字比例、平移或旋轉
為文字縮放、平移或旋轉文字時,請將 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
lambda:
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
會在可組合項進入組合時執行。系統會在可組合項啟動時啟動動畫,您可以使用此程式碼推動動畫狀態變更。將 Animatable
與 animateTo
方法搭配使用,即可在啟動時啟動動畫:
val alphaAnimation = remember { Animatable(0f) } LaunchedEffect(Unit) { alphaAnimation.animateTo(1f) } Box( modifier = Modifier.graphicsLayer { alpha = alphaAnimation.value } )
建立連續動畫
使用 Animatable
協同程式 API 執行依序或並行動畫。在 Animatable
上逐一呼叫 animateTo
,會導致每個動畫等待先前的動畫結束,再繼續操作。因為這是暫停函式。
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 來使用相同的狀態,同時驅動許多不同的屬性動畫。以下範例為由狀態變更 (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
的 lambda 版本。這樣做會略過重組程序,並在組合階段外執行動畫,否則請使用 Modifier.graphicsLayer{ }
,因為這個修飾符一律會在繪圖階段中執行。如要進一步瞭解相關資訊,請參閱效能說明文件中的「延遲讀取」一節。
變更動畫時間
根據預設,Compose 會使用 spring 動畫來處理大部分的動畫。彈跳或物理動畫可以更自然。這些物件也可能中斷,因為系統會將物件目前的速率 (而非固定時間) 納入考量。如要覆寫預設值,以上示範的所有動畫 API 都可以設定 animationSpec
來自訂動畫的執行方式,無論要在一段時間內執行動畫,還是要更活靈活現。
以下摘要說明不同的 animationSpec
選項:
spring
:以物理為基礎的動畫,所有動畫的預設元素。您可以變更硬度或 dampingRatio,藉此呈現不同的動畫外觀與風格。tween
(「介於」的短):以時間長度為基礎的動畫,使用Easing
函式在兩個值之間建立動畫。keyframes
:指定動畫中特定資料點值的規格。repeatable
:以時間為基礎的規格,執行特定次數 (由RepeatMode
指定)。infiniteRepeatable
:永久執行的以時間長度為準規格。snap
:立即貼齊結束值,不含任何動畫。
如要進一步瞭解 animationSpecs,請參閱完整說明文件。
其他資源
如需更多 Compose 中有趣的動畫範例,請查看下列內容: