I have this interesting problem in a project, where user should be able to draw the same shape over the defined shape, i have achieved this so far, but i want to check if he/she drawn over the shape correctly in ONE GO. if the finger goes outside the sqaure the current drawing should reset and put a toast message as unsucssesfull else says succesfull, How do i check if the drawing is on the Square?
The white square is drawn with drawRect() Method and drawing over it is by the user itself, achieved by Drawpath(). code is given below
class DrawingActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyDrawing()
}
}
}
@Composable
fun MyDrawing() {
val actionIdle = 0
val actionDown = 1
val actionMove = 2
val actionUp = 3
//Path, current touch position and touch states
val path = remember { Path() }
var motionEvent by remember { mutableStateOf(actionIdle) }
var currentPosition by remember { mutableStateOf(Offset.Unspecified) }
val canvasColor: Color by remember { mutableStateOf(Color.LightGray) }
val drawModifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.background(canvasColor)
.clipToBounds()
.pointerInput(Unit) {
forEachGesture {
awaitPointerEventScope {
val down: PointerInputChange = awaitFirstDown().also {
motionEvent = actionDown
currentPosition = it.position
}
do {
val event: PointerEvent = awaitPointerEvent()
var eventChanges =
"DOWN changedToDown: ${down.changedToDown()} changedUp: ${down.changedToUp()}\n"
event.changes
.forEachIndexed { index: Int, pointerInputChange: PointerInputChange ->
eventChanges += "Index: $index, id: ${pointerInputChange.id}, " +
"changedUp: ${pointerInputChange.changedToUp()}" +
"pos: ${pointerInputChange.position}\n"
pointerInputChange.consumePositionChange()
}
//gestureText = "EVENT changes size ${event.changes.size}\n" + eventChanges
//gestureColor = Color.Green
motionEvent = actionMove
currentPosition = event.changes.first().position
} while (event.changes.any { it.pressed })
motionEvent = actionUp
//canvasColor = Color.LightGray
//gestureText += "UP changedToDown: ${down.changedToDown()} " + "changedUp: ${down.changedToUp()}\n"
}
}
}
Canvas(
modifier = drawModifier
.padding(20.dp)
.size(500.dp)
) {
val canvasWidth = size.width
val canvasHeight = size.height
val line = 1.5
val squareSize = canvasWidth/line
drawRect(
color = Color.White,
topLeft = Offset(center.x - canvasWidth / 3, center.y - canvasHeight / 6),
size = Size(width = squareSize.toFloat(), squareSize.toFloat()),
style = Stroke(
width = 50.dp.toPx()
),
)
when(motionEvent){
actionDown->{
path.moveTo(currentPosition.x,currentPosition.y)
}
actionMove->{
if (currentPosition!= Offset.Unspecified){
path.lineTo(currentPosition.x,currentPosition.y)
}
}
actionUp->{
path.lineTo(currentPosition.x,currentPosition.y)
motionEvent = actionIdle
}
else-> Unit
}
drawPath(
color = Color.Cyan,
path = path,
style = Stroke(width = 5.dp.toPx(), join = StrokeJoin.Round)
)
}
}