Skip to content

Instantly share code, notes, and snippets.

@maiatoday
Created May 26, 2022 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maiatoday/58efb601f46161a3455b58fe71c86f95 to your computer and use it in GitHub Desktop.
Save maiatoday/58efb601f46161a3455b58fe71c86f95 to your computer and use it in GitHub Desktop.
GlitterBox
@Composable
fun GlitterBox(
rainbow: List<Color> = SkittlesRainbow,
fleckCount: Int = 2,
visible: Boolean = true
) {
var size by remember { mutableStateOf(Size.Zero) }
var source by remember { mutableStateOf(Offset(200f, 200f)) }
var glitterState by remember {
mutableStateOf(
GlitterState(
speed = 0.5f,
colors = rainbow,
glitterShape = GlitterShape.Mixed,
fleckCount = fleckCount,
source = source
)
)
}
var lastFrame by remember { mutableStateOf(-1L) }
LaunchedEffect(visible) {
while (visible && isActive) {
withFrameMillis { newTick ->
val elapsedMillis = newTick - lastFrame
val wasFirstFrame = lastFrame < 0
lastFrame = newTick
if (wasFirstFrame) return@withFrameMillis
glitterState.next(elapsedMillis)
}
}
}
Box(
Modifier
.fillMaxSize()
.onSizeChanged { size = it.toSize() }
) {
Canvas(
modifier = Modifier
.fillMaxSize()
) {
glitterState = glitterState.sizeChanged(this.size)
if (visible) {
for (fleck in glitterState.flecks) {
fleck.draw(drawContext.canvas)
}
}
}
Box(
Modifier
.offset { source.round() }
.size(10.dp)
.background(Color.Magenta)
.pointerInput(Unit) {
detectDragGestures { _, dragAmount ->
val summed = source + dragAmount
val newValue = Offset(
x = summed.x.coerceIn(0f, size.width - 10.dp.toPx()),
y = summed.y.coerceIn(0f, size.height - 10.dp.toPx())
)
source = newValue
glitterState = glitterState.updateSource(source)
}
}
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment