Home > Blockchain >  Jetpack compose draw circle with pulsing animation ( view doesn’t want to go of screen )
Jetpack compose draw circle with pulsing animation ( view doesn’t want to go of screen )

Time:02-22

I'm trying to animate a circle expanding out of the screen, so far I found the code that can do that but the problem is that the circle "max"s out and even brakes its form.

@Composable
fun BallScaleIndicator() {
    var targetValue by remember { mutableStateOf(0f) }
    // Update the attribute on the animation
    val animationProgress by animateFloatAsState(
        targetValue = targetValue,
        animationSpec = infiniteRepeatable(
            animation = tween(durationMillis = 1000)
        )
    )
    SideEffect { targetValue = 1f }
    Ball(
        modifier = Modifier
            .scale(animationProgress)
            .alpha(1 - animationProgress),
    )
}


@Composable
fun Ball(
    modifier: Modifier = Modifier,
    size: Dp = LocalConfiguration.current.screenHeightDp.dp,
    backgroundColor: Color = colorResource(id = R.color.black),
) {
    Box(contentAlignment = Alignment.Center,
        modifier = modifier
            .width(size)
            .height(size)
            .border(BorderStroke(1.dp, backgroundColor), CircleShape)
    ) {
    }
}

I use the BallScaleIndicator as the only content.

and the result is this, when size ( Ball param ) is screenWidthDp

but I get this when size is screenHeightDp

( those are animation that I captured during animation, they will expend to the max screen size )

I want the animation to remain a circle and go out of the screen. How can I achieve this?

CodePudding user response:

You can achieve this behavior using canvas in jetpack compose

Canvas(modifier = Modifier.fillMaxSize()) {
       drawCircle(
               color = Color.Black,
               center = Offset(size.width/2, size.height/2),
               radius = 10f)
       }

Here you can manipulate the value in radius and achieve what you desired.

CodePudding user response:

After many tries I found a code that works. Not sure if all of it is necessary but it works

     @Composable
   fun PulsatingCircle(delay: Int = 0) {
      val scale = LocalConfiguration.current.screenHeightDp.toFloat()
var targetValue by remember { mutableStateOf(0f) }

val animationProgress by animateFloatAsState(
    targetValue = targetValue,
    animationSpec = infiniteRepeatable(
        animation = tween(durationMillis = 3000, delayMillis = delay),

    ),
)
SideEffect { targetValue = 1f }
Canvas(modifier = Modifier
    .fillMaxSize()
    .scale(animationProgress)
) {
    drawCircle(
        color = Color(0f,0f,0f, 1 - animationProgress),
        center = center,
        radius = scale,
        style = Stroke(2f))
}

}

  • Related