Compose 绘制Loading

185 阅读1分钟
package com.show.elephantcallershowdemo

import android.util.Log
import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.onPlaced
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay


@Composable
fun createTestLoading(){

    var size by remember {
        mutableStateOf( IntSize(0,0))
    }
    Box(modifier = Modifier
        .fillMaxWidth()
        .height(50.dp)
        .onPlaced {
            size = it.size
        },
        contentAlignment = Alignment.CenterStart
    ){
        createEachCircle(size.width,size.height,200)
        createEachCircle(size.width,size.height,400)
        createEachCircle(size.width,size.height,600)
        createEachCircle(size.width,size.height,800)
        createEachCircle(size.width,size.height,1000)
    }
}

@Composable
fun createEachCircle(xOffset:Int,yOffset:Int,delayMillis:Int){
    val anim = remember {
        Animatable(0f)
    }
    val yAnim = remember {
        Animatable(-0.5f)
    }
    // x动画
    LaunchedEffect(key1 = Unit, block = {
        delay(delayMillis * 1L)
        Log.e("ccccccc","延迟完毕")
        anim.animateTo(1f, tween(12000, easing = LinearEasing))
        yAnim.stop()
    })

    // y动画
    LaunchedEffect(key1 = Unit, block = {
        delay(delayMillis * 1L)
        Log.e("ccccccc","延迟完毕2")
        yAnim.animateTo(0.5f, animationSpec = infiniteRepeatable(tween(1000), repeatMode = RepeatMode.Reverse))
    })

    Box(modifier = Modifier
        .size(10.dp)
        .offset {
           IntOffset((anim.value * xOffset).toInt(), (yOffset * yAnim.value).toInt())
        }
        .drawBehind {
            drawCircle(color = Color.Red, radius = size.height / 2)
        })
}

8b42a4c905feb46b25282c107ec15905.gif