Advertisement
Guest User

Untitled

a guest
Feb 26th, 2022
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.67 KB | None | 0 0
  1. class MainActivity : ComponentActivity() {
  2.   override fun onCreate(savedInstanceState: Bundle?) {
  3.     super.onCreate(savedInstanceState)
  4.  
  5.     setContent {
  6.       ComposePlaygroundTheme {
  7.         val zoomContentState = remember { ZoomContentState() }
  8.  
  9.         ZoomableContent(zoomContentState) {
  10.           Text(
  11.             modifier = Modifier.clickable { zoomContentState.zoomIn() },
  12.             text = "Test text"
  13.           )
  14.         }
  15.       }
  16.     }
  17.  
  18.   }
  19. }
  20.  
  21. @Composable
  22. fun ZoomableContent(
  23.   zoomContentState: ZoomContentState,
  24.   duration: Int = 50,
  25.   content: @Composable () -> Unit
  26. ) {
  27.   var scale by remember { mutableStateOf(1f) }
  28.  
  29.   LaunchedEffect(zoomContentState) {
  30.     zoomContentState.zoomEventsFlow.collectLatest { zoomData ->
  31.       animate(
  32.         initialValue = 0f,
  33.         targetValue = 1f,
  34.         initialVelocity = 0f,
  35.         animationSpec = tween(durationMillis = duration, easing = LinearEasing),
  36.         block = { progress, _ ->
  37.           if (progress < 0.5f) {
  38.             // zoom in
  39.             scale = lerpF(1f, zoomData.value, progress * 2)
  40.           } else {
  41.             // zoom back out
  42.             scale = lerpF(zoomData.value, 1f, (progress * 2) - 1f)
  43.           }
  44.         }
  45.       )
  46.     }
  47.   }
  48.  
  49.   Box(modifier = Modifier.scale(scale)) {
  50.     content()
  51.   }
  52. }
  53.  
  54. private fun lerpF(from: Float, to: Float, progress: Float): Float {
  55.   return from + progress * (to - from)
  56. }
  57.  
  58. class ZoomContentState {
  59.   val zoomEventsFlow = MutableSharedFlow<ZoomData>(extraBufferCapacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)
  60.  
  61.   fun zoomIn() {
  62.     zoomEventsFlow.tryEmit(ZoomData(1.5f))
  63.   }
  64. }
  65.  
  66. data class ZoomData(val value: Float)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement