[demo] Improve painting demo slightly

This commit is contained in:
Emil Ernerfeldt 2021-02-28 19:50:47 +01:00
parent e417fac52e
commit 1fb3b43dfc

View file

@ -18,24 +18,24 @@ impl Default for Painting {
} }
impl Painting { impl Painting {
pub fn ui_control(&mut self, ui: &mut Ui) { pub fn ui_control(&mut self, ui: &mut egui::Ui) -> egui::Response {
ui.horizontal(|ui| { ui.horizontal(|ui| {
egui::stroke_ui(ui, &mut self.stroke, "Stroke"); egui::stroke_ui(ui, &mut self.stroke, "Stroke");
ui.separator(); ui.separator();
if ui.button("Clear Painting").clicked() { if ui.button("Clear Painting").clicked() {
self.lines.clear(); self.lines.clear();
} }
}); })
.response
} }
pub fn ui_content(&mut self, ui: &mut Ui) { pub fn ui_content(&mut self, ui: &mut Ui) -> egui::Response {
let (response, painter) = let (mut response, painter) =
ui.allocate_painter(ui.available_size_before_wrap_finite(), Sense::drag()); ui.allocate_painter(ui.available_size_before_wrap_finite(), Sense::drag());
let rect = response.rect;
let to_screen = emath::RectTransform::from_to( let to_screen = emath::RectTransform::from_to(
Rect::from_min_size(Pos2::ZERO, rect.square_proportions()), Rect::from_min_size(Pos2::ZERO, response.rect.square_proportions()),
rect, response.rect,
); );
let from_screen = to_screen.inverse(); let from_screen = to_screen.inverse();
@ -49,17 +49,23 @@ impl Painting {
let canvas_pos = from_screen * pointer_pos; let canvas_pos = from_screen * pointer_pos;
if current_line.last() != Some(&canvas_pos) { if current_line.last() != Some(&canvas_pos) {
current_line.push(canvas_pos); current_line.push(canvas_pos);
response.mark_changed();
} }
} else if !current_line.is_empty() { } else if !current_line.is_empty() {
self.lines.push(vec![]); self.lines.push(vec![]);
response.mark_changed();
} }
let mut shapes = vec![];
for line in &self.lines { for line in &self.lines {
if line.len() >= 2 { if line.len() >= 2 {
let points: Vec<Pos2> = line.iter().map(|p| to_screen * *p).collect(); let points: Vec<Pos2> = line.iter().map(|p| to_screen * *p).collect();
painter.add(Shape::line(points, self.stroke)); shapes.push(egui::Shape::line(points, self.stroke));
} }
} }
painter.extend(shapes);
response
} }
} }