I am trying to implement an interactive Canvas component in Jetpack Compose to capture user click events and draw content on the Canvas. I used pointerInput to detect click events and applied the click coordinates to the drawing function. However, I found that the captured click coordinates do not match the actual drawing position.
enter image description here
@Composable
fun ColumnScreen() {
Column {
TestCanvas()
TestCanvas()
TestCanvas()
Spacer(Modifier.height(200.dp))
TestCanvas()
}
}
@Composable
fun TestCanvas() {
val textMeasurer = rememberTextMeasurer()
val points = remember { mutableStateListOf<Offset>() }
Canvas(Modifier.width(150.dp).height(150.dp)
.pointerInput(Unit) {
detectTapGestures {
points.add(it)
}
}
) {
drawRect(Color.Blue, topLeft = Offset.Zero, Size(200f, 200f))
points.forEach {
drawText(textMeasurer, it.toString(), it, style = TextStyle(color = Color.Green))
drawCircle(Color.Red, 5f, it)
}
}
}
use org.jetbrains.compose:1.6.0
If my canvas is further from the top, the y value deviation increases. However, I tried using Row and found that there was no deviation in the x value.
What exactly is the problem?
I tried placing the canvas inside a Column, and noticed that the y-coordinate of the clicked point deviates more from the drawn coordinate the farther it is from the top. In the image, I attempted to click the middle point at the bottom of each blue rectangle, and theoretically their x and y coordinates should be close or even the same, but in reality, there is a significant deviation. However, when placing the canvas inside a Row, the x-coordinate does not have any deviation.
bvin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.