I'm trying to create a sky view in my Android app using Jetpack Compose. I want to display it inside a Card
with a fixed height
. During nigth time, the card background turns dark blue and I'd like to have some blinking stars spread over the sky.
To create the stars blinking animation, I'm using an InfiniteTransition
object and a scale
property with animateFloat
that I apply to several Icon
s. Those Icon
s are created inside a BoxWithConstraints
, to spread then randomly using a for
loop. The full code I'm using is shown below:
@Composable
fun NightSkyCard() {
Card(
modifier = Modifier
.height(200.dp)
.fillMaxWidth(),
elevation = 2.dp,
shape = RoundedCornerShape(20.dp),
backgroundColor = DarkBlue
) {
val infiniteTransition = rememberInfiniteTransition()
val scale by infiniteTransition.animateFloat(
initialValue = 1f,
targetValue = 0f,
animationSpec = infiniteRepeatable(
animation = tween(1000),
repeatMode = RepeatMode.Reverse
)
)
BoxWithConstraints(
modifier = Modifier.fillMaxSize()
) {
for (n in 0..20) {
val size = Random.nextInt(3, 5)
val start = Random.nextInt(0, maxWidth.value.toInt())
val top = Random.nextInt(10, maxHeight.value.toInt())
Icon(
imageVector = Icons.Filled.Circle,
contentDescription = null,
modifier = Modifier
.padding(start = start.dp, top = top.dp)
.size(size.dp)
.scale(scale),
tint = Color.White
)
}
}
}
}
The problem with this code is that the BoxWithConstraints
's scope is recomposing continously, so I get a lot of dots appearing and dissapearing from the screen very fast. I'd like the scope to just run once, so that the dots created at first time would blink using the scale
property animation. How could I achieve that?
durationMillis
parameter oftween
property a random float as well, but I won't be able to call theanimateFloat()
function inside the DrawScope. Any suggestion? – Casteel