如何通过PointerInputScope底层方式获取MotionEvent触摸尺寸?
能否通过PointerInput获取与MotionEvent一致的触摸尺寸值?
可以,但PointerInputScope自带的size属性是当前组件的尺寸(IntSize类型),和MotionEvent的触摸尺寸完全无关。要获取和MotionEvent的size一致的触摸尺寸数据,需要从PointerEvent的指针输入变更中提取对应参数。
原理说明
MotionEvent的size是触摸接触区域的相对尺寸(范围0-1),由触摸接触椭圆的长轴(touchMajor)和短轴(touchMinor)计算而来。在Compose的PointerInput体系中,我们可以通过PointerInputChange对象的pointerProperties获取到像素单位的touchMajor和touchMinor,对应MotionEvent的getTouchMajor()和getTouchMinor()方法返回值;如果需要和MotionEvent的size完全一致的相对值,只需将这两个像素值转换为相对比例即可。
实现示例
fun ProductsList() { val resources = LocalContext.current.resources Column( modifier = Modifier .pointerInput(Unit) { awaitPointerEventScope { while (true) { val pointerEvent = awaitPointerEvent() pointerEvent.changes.forEach { change -> // 获取触摸接触区域的长轴/短轴(像素单位) val touchMajor = change.pointerProperties.touchMajor val touchMinor = change.pointerProperties.touchMinor // 计算与MotionEvent.size一致的相对尺寸值 val displayMetrics = resources.displayMetrics val maxScreenSize = max(displayMetrics.widthPixels, displayMetrics.heightPixels).toFloat() val motionEventStyleSize = (touchMajor + touchMinor) / (2 * maxScreenSize) // 这里即可使用motionEventStyleSize(和MotionEvent.size逻辑一致) } } } } ) { // 列表内容 } }
补充说明
- 特定手势场景适配:如果只需处理点击、拖拽等特定手势,也可以使用
detectTapGestures、detectDragGestures等高阶函数,在回调中直接获取PointerInputChange对象提取参数,示例如下:
fun ProductsList() { Column( modifier = Modifier .pointerInput(Unit) { detectTapGestures( onDown = { val touchMajor = currentEvent.changes.first().pointerProperties.touchMajor // 处理触摸尺寸 } ) } ) { // 列表内容 } }
- 设备兼容性:部分设备可能不支持触摸尺寸检测,会返回默认值(如0),需要做好兼容处理。
内容的提问来源于stack exchange,提问作者Júlio César
相关产品推荐
相关产品推荐

