在添加矩形后,我们可以对其进行拖拽:egui::CentralPanel::default().show(ctx, |ui| {
let response = ui.allocate_rect(ui.max_rect(), egui::Sense::hover());
let to_screen = egui::emath::RectTransform::from_to(
egui::Rect::from_min_size(egui::Pos2::ZERO, response.rect.size()),
response.rect,
);
let shape = ui.painter().add(egui::Shape::Noop);
let rounding_radius = 4.0;
let rounding = egui::Rounding::same(rounding_radius);
let mut body_rect = egui::Rect::from_min_size(
egui::Pos2 { x: 10.0, y: 100.0 },
egui::vec2(100.0, 200.0),
);
body_rect = to_screen.transform_rect(body_rect);
let window_response = ui.interact(
body_rect,
egui::Id::new((1, "window")),
egui::Sense::click_and_drag(),
);
let drag_delta = window_response.drag_delta();
if drag_delta.length_sq() > 0.0 {
body_rect = body_rect.translate(drag_delta);
}
let body = egui::Shape::Rect(egui::epaint::RectShape {
rect: body_rect,
rounding: rounding,
fill: color_from_hex("#3f3f3f").unwrap(),
stroke: egui::Stroke::NONE,
});
ui.painter().set(shape, body);
});
但是好像拖不动,这是因为每次update的时候,我们定义的矩形位置都是固定的:let mut body_rect = egui::Rect::from_min_size(
egui::Pos2 { x: 10.0, y: 100.0 },
egui::vec2(100.0, 200.0),
);
因此我们需要记下上一次的位置:pub struct TemplateApp {
#[serde(skip)]
rect_pos: egui::Pos2,
}
然后在创建矩形的时候使用上一次的位置:egui::CentralPanel::default().show(ctx, |ui| {
let response = ui.allocate_rect(ui.max_rect(), egui::Sense::hover());
let to_screen = egui::emath::RectTransform::from_to(
egui::Rect::from_min_size(egui::Pos2::ZERO, response.rect.size()),
response.rect,
);
let shape = ui.painter().add(egui::Shape::Noop);
let rounding_radius = 4.0;
let rounding = egui::Rounding::same(rounding_radius);
let mut body_rect = egui::Rect::from_min_size(
self.rect_pos,
egui::vec2(100.0, 200.0),
);
body_rect = to_screen.transform_rect(body_rect);
let window_response = ui.interact(
body_rect,
egui::Id::new((1, "window")),
egui::Sense::click_and_drag(),
);
let drag_delta = window_response.drag_delta();
if drag_delta.length_sq() > 0.0 {
body_rect = body_rect.translate(drag_delta);
self.rect_pos = self.rect_pos + drag_delta;
}
let body = egui::Shape::Rect(egui::epaint::RectShape {
rect: body_rect,
rounding: rounding,
fill: color_from_hex("#3f3f3f").unwrap(),
stroke: egui::Stroke::NONE,
});
ui.painter().set(shape, body);
});