From 19ce3657fa4b7f29dc0e949fa4742dfa7155817a Mon Sep 17 00:00:00 2001 From: Enrico Lumetti Date: Sun, 8 Nov 2020 14:48:30 +0100 Subject: [PATCH] Account for stroke thickness in bounding box --- src/main.rs | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/src/main.rs b/src/main.rs index 20e2238..0e87c24 100644 --- a/src/main.rs +++ b/src/main.rs @@ -29,30 +29,33 @@ mod stiletto { #[derive(Clone, druid::Data)] pub enum CanvasElement { - Freehand(Path), + Freehand { + path: Path, + thickness: f64 + } } impl CanvasElement { pub fn bounding_box(&self) -> druid::Rect { match self { - CanvasElement::Freehand(p) => { + CanvasElement::Freehand{ path, thickness } => { use druid::kurbo::Shape; - p.kurbo_path.bounding_box() + path.kurbo_path.bounding_box().inflate(*thickness, *thickness) } } } pub fn draw(&self, ctx: &mut druid::PaintCtx) { match self { - CanvasElement::Freehand(p) => { + CanvasElement::Freehand{ path, thickness } => { let stroke_color = druid::Color::rgb8(0, 128, 0); - ctx.stroke(&p.kurbo_path, &stroke_color, 2.0); + ctx.stroke(&path.kurbo_path, &stroke_color, *thickness); } } } pub fn get_path_mut(&mut self) -> Option<&mut Path> { match self { - CanvasElement::Freehand(p) => Some(p), + CanvasElement::Freehand{ path, .. } => Some(path), } } } @@ -80,7 +83,10 @@ impl Widget for CanvasWidget { Event::MouseDown(mouse_event) => { let mut kurbo_path = BezPath::new(); kurbo_path.move_to((mouse_event.pos.x, mouse_event.pos.y)); - data.current_element = Some(CanvasElement::Freehand(stiletto::Path { kurbo_path })); + data.current_element = Some(CanvasElement::Freehand{ + path: stiletto::Path { kurbo_path }, + thickness: 2.0, + }); } Event::MouseMove(mouse_event) => { if data.is_drawing() { @@ -125,9 +131,9 @@ impl Widget for CanvasWidget { return; } if data.is_drawing() { - data.current_element.as_ref().map(|e| { + if let Some(e) = data.current_element.as_ref() { ctx.request_paint_rect(e.bounding_box()); - }); + } } else { ctx.request_paint(); }