Skip to content

Instantly share code, notes, and snippets.

@agarasul
Created December 13, 2023 14:01
Show Gist options
  • Save agarasul/a0a070e0d6c0a61d1a3fc2d5a2932aa3 to your computer and use it in GitHub Desktop.
Save agarasul/a0a070e0d6c0a61d1a3fc2d5a2932aa3 to your computer and use it in GitHub Desktop.
Map Drawer Part 2
@Composable
fun MapDrawer(onDrawingEnd : (List<Point>) -> Unit) {
var state by remember { mutableStateOf(MapPolygonState()) }
val brush = remember { SolidColor(Color.Black) }
val path = remember { Path() }
Canvas(
modifier = Modifier
.fillMaxSize()
.pointerInput(Unit) {
awaitEachGesture {
val screenPoints = mutableListOf<Point>()
awaitPointerEvent().changes
.first()
.also { changes ->
val position = changes.position
screenPoints.add(position.toPoint())
state = state.copy(
currentPosition = position,
event = DrawerMotionEvent.down
)
}
do {
val event: PointerEvent = awaitPointerEvent()
event.changes.forEach { changes ->
val position = changes.position
screenPoints.add(position.toPoint())
state = state.copy(
currentPosition = position,
event = DrawerMotionEvent.move
)
}
} while (event.changes.any { it.pressed })
currentEvent.changes
.first()
.also { change ->
state = state.copy(
currentPosition = change.position,
event = DrawerMotionEvent.up
)
screenPoints.add(change.position.toPoint())
}
onDrawingEnd.invoke(screenPoints)
}
},
onDraw = {
when (state.event) {
DrawerMotionEvent.idle -> Unit
DrawerMotionEvent.up, DrawerMotionEvent.move -> path.lineTo(
state.currentPosition.x,
state.currentPosition.y
)
DrawerMotionEvent.down -> path.moveTo(
state.currentPosition.x,
state.currentPosition.y
)
}
drawPath(
path = path,
brush = brush,
style = Stroke(width = 5f)
)
}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment