Yasutaka Kawamoto
06/27/2021, 4:10 AMdrawRect
in Canvas?
Canvas(modifier = Modifier.fillMaxSize()) {
list?.forEach { item ->
val bounds = item.bounds // Rect
// I want to click this
drawRect(
color = Color.Blue,
topLeft = Offset(x = bounds.left, y = <http://bounds.top|bounds.top>),
size = Size(bounds.width(), bounds.height()),
)
}
}
Zach Klippenstein (he/him) [MOD]
06/27/2021, 4:46 AMModifier.pointerInput
to get touch events, check the coordinates for your rect bounds.Yasutaka Kawamoto
06/27/2021, 5:55 AM@Composable
fun PreviewImage(list: List<Item>?) {
Canvas(modifier = Modifier
.fillMaxSize()
// Added
.pointerInput(Unit) {
detectTapGestures(
onTap = { offset ->
val selectedItem = list?.firstOrNull { it.bounds.contains(offset.x, offset.y) }
Timber.d("offset = $offset, list = $list, selectedItem=$selectedItem")
// offset = Offset(472.0, 451.0), list = null, selectedItem=null
// Why the list is null?
}
)
}) {
// This list is not null.
list?.forEach { item ->
val bounds = item.bounds // Rect
drawRect(
color = Color.Blue,
topLeft = Offset(x = bounds.left, y = <http://bounds.top|bounds.top>),
size = Size(bounds.width(), bounds.height()),
)
}
}
}
Do you have any ideas?Yasutaka Kawamoto
06/27/2021, 8:39 AM@Composable
fun PreviewImage(list: List<Item>?) {
var results by remember { mutableStateOf<List<Item>?>(null)}
Canvas(modifier = Modifier
.fillMaxSize()
.pointerInput(Unit) {
detectTapGestures(
onTap = { offset ->
val selectedItem = results?.firstOrNull { it.bounds.contains(offset.x, offset.y) }
Timber.d("offset = $offset, list = $results, selectedItem=$selectedItem")
}
)
}) {
list?.forEach { item ->
val bounds = item.bounds // Rect
drawRect(
color = Color.Blue,
topLeft = Offset(x = bounds.left, y = <http://bounds.top|bounds.top>),
size = Size(bounds.width(), bounds.height()),
)
}
results = list
}
}
Zach Klippenstein (he/him) [MOD]
06/27/2021, 5:02 PMrememberUpdatedState
to do this as well – it’s the same idea but in a single line. https://developer.android.com/jetpack/compose/side-effects#rememberupdatedstateYasutaka Kawamoto
06/29/2021, 12:30 AM@Composable
fun PreviewImage(list: List<Item>?) {
val results by rememberUpdatedState(newValue = list)
Canvas(modifier = Modifier
.fillMaxSize()
.pointerInput(Unit) {
detectTapGestures(
onTap = { offset ->
val selectedItem = results?.firstOrNull { it.bounds.contains(offset.x, offset.y) }
Timber.d("offset = $offset, list = $results, selectedItem=$selectedItem")
}
)
}) {
results?.forEach { item ->
val bounds = item.bounds // Rect
drawRect(
color = Color.Blue,
topLeft = Offset(x = bounds.left, y = <http://bounds.top|bounds.top>),
size = Size(bounds.width(), bounds.height()),
)
}
}
}