Skip to content

Instantly share code, notes, and snippets.

@AhmedMourad0
Last active March 2, 2024 16:49
Show Gist options
  • Save AhmedMourad0/d45fce4f1b8f1a8e0eb87814f1cd7d2f to your computer and use it in GitHub Desktop.
Save AhmedMourad0/d45fce4f1b8f1a8e0eb87814f1cd7d2f to your computer and use it in GitHub Desktop.
Code snippet for the `Leveraging the Power of Snapshots in Jetpack Compose` Medium article.
@Composable
fun StickerBoard(
stickers: List<Sticker>,
modifier: Modifier = Modifier
) {
Box(modifier.fillMaxWidth().background(Color.White).clipToBounds()) {
stickers.forEach { sticker ->
key(sticker.id) {
Sticker(sticker)
}
}
}
}
@Composable
private fun Sticker(
sticker: Sticker,
modifier: Modifier = Modifier
) {
when (val type = sticker.type) {
is StickerType.Shape -> Box(modifier = modifier
.sticker(sticker)
.background(type.color, type.shape)
.border(type.borderWidth, type.borderColor, type.shape)
)
//images and other types go here
}
}
@Composable
private fun Modifier.sticker(
sticker: Sticker
) = this.zIndex(sticker.zIndex.toFloat()).graphicsLayer {
this.translationX = sticker.x
this.translationY = sticker.y
this.scaleX = sticker.scaleX
this.scaleY = sticker.scaleY
this.rotationZ = sticker.rotationZ
}.pointerInput("DragDetector") {
detectDragGestures(onDrag = { _, dragAmount ->
sticker.offset += dragAmount
.rotateBy(sticker.rotationZ)
.times(Offset(sticker.scaleX, sticker.scaleY))
})
}.transformable(state = rememberTransformableState { zoomChange, _, rotationChange ->
sticker.scaleX *= zoomChange
sticker.scaleY *= zoomChange
sticker.rotationZ += rotationChange
}, canPan = { false }).size(sticker.width, sticker.height)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment