如何在nannou中处理触摸板滚动?解决PhysicalPosition类型不匹配问题
在nannou中处理触摸板滚动事件的问题解决
问题
笔记本触摸板滚动触发的事件格式为:
MouseWheel(PixelDelta(PhysicalPosition(x, y)), Moved)
在nannou中找不到PhysicalPosition结构体,尝试引入winit::dpi::PhysicalPosition时出现类型不匹配错误:
expected `PhysicalPosition<f64>`, found a different `PhysicalPosition<f64>`
最小示例代码
use nannou::prelude::{ App, Frame, WindowEvent, WindowId, BLACK, MouseScrollDelta::LineDelta, MouseScrollDelta::PixelDelta, MouseWheel, }; use winit::dpi::PhysicalPosition; fn main() { nannou::app(model).run(); } struct Model { _window: WindowId } fn model(app: &App) -> Model { let _window = app.new_window().view(view).event(event).build().unwrap(); Model { _window } } fn view(app: &App, _model: &Model, frame: Frame) { frame.clear(BLACK); let draw = app.draw(); draw.to_frame(app, &frame).unwrap(); } fn event(_app: &App, _model: &mut Model, event: WindowEvent) { //println!("{:?}", event); match event { MouseWheel(LineDelta(x, y), ..) => { println!("{event:?} - x,y: {x}, {y}"); } MouseWheel(PixelDelta(PhysicalPosition::<f64>{ x, y }), ..) => { println!("{event:?} - x,y: {x}, {y}"); } _ => (), } }
编译错误
error[E0308]: mismatched types --> src/main.rs:28:24 | 24 | match event { | ----- this expression has type `nannou::event::WindowEvent` ... 28 | MouseWheel(PixelDelta(PhysicalPosition::<f64>{ x, y }), ..) => { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `PhysicalPosition<f64>`, found a different `PhysicalPosition<f64>`
错误原因
本质是crate版本不一致导致的类型不兼容:你直接导入的winit::dpi::PhysicalPosition和nannou内部依赖的winit版本导出的PhysicalPosition是两个完全独立的类型,即使名字和结构一致,Rust也会判定为不同类型。
解决方法
不要直接引入外部winit的类型,改用nannou重新导出的PhysicalPosition:
- 直接从
nannou::prelude中导入,或者通过nannou::winit::dpi::PhysicalPosition引用。
修改后的代码
use nannou::prelude::{ App, Frame, WindowEvent, WindowId, BLACK, MouseScrollDelta::LineDelta, MouseScrollDelta::PixelDelta, MouseWheel, PhysicalPosition, // 从nannou的prelude导入对应类型 }; fn main() { nannou::app(model).run(); } struct Model { _window: WindowId } fn model(app: &App) -> Model { let _window = app.new_window().view(view).event(event).build().unwrap(); Model { _window } } fn view(app: &App, _model: &Model, frame: Frame) { frame.clear(BLACK); let draw = app.draw(); draw.to_frame(app, &frame).unwrap(); } fn event(_app: &App, _model: &mut Model, event: WindowEvent) { match event { MouseWheel(LineDelta(x, y), ..) => { println!("{event:?} - x,y: {x}, {y}"); } MouseWheel(PixelDelta(PhysicalPosition::<f64>{ x, y }), ..) => { println!("{event:?} - x,y: {x}, {y}"); } _ => (), } }
内容的提问来源于stack exchange,提问作者Raf
相关产品推荐
相关产品推荐

