Account for stroke thickness in bounding box

This commit is contained in:
Enrico Lumetti 2020-11-08 14:48:30 +01:00
parent 2ef210b7ad
commit 19ce3657fa
1 changed files with 15 additions and 9 deletions

View File

@ -29,30 +29,33 @@ mod stiletto {
#[derive(Clone, druid::Data)] #[derive(Clone, druid::Data)]
pub enum CanvasElement { pub enum CanvasElement {
Freehand(Path), Freehand {
path: Path,
thickness: f64
}
} }
impl CanvasElement { impl CanvasElement {
pub fn bounding_box(&self) -> druid::Rect { pub fn bounding_box(&self) -> druid::Rect {
match self { match self {
CanvasElement::Freehand(p) => { CanvasElement::Freehand{ path, thickness } => {
use druid::kurbo::Shape; 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) { pub fn draw(&self, ctx: &mut druid::PaintCtx) {
match self { match self {
CanvasElement::Freehand(p) => { CanvasElement::Freehand{ path, thickness } => {
let stroke_color = druid::Color::rgb8(0, 128, 0); 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> { pub fn get_path_mut(&mut self) -> Option<&mut Path> {
match self { match self {
CanvasElement::Freehand(p) => Some(p), CanvasElement::Freehand{ path, .. } => Some(path),
} }
} }
} }
@ -80,7 +83,10 @@ impl Widget<CanvasData> for CanvasWidget {
Event::MouseDown(mouse_event) => { Event::MouseDown(mouse_event) => {
let mut kurbo_path = BezPath::new(); let mut kurbo_path = BezPath::new();
kurbo_path.move_to((mouse_event.pos.x, mouse_event.pos.y)); 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) => { Event::MouseMove(mouse_event) => {
if data.is_drawing() { if data.is_drawing() {
@ -125,9 +131,9 @@ impl Widget<CanvasData> for CanvasWidget {
return; return;
} }
if data.is_drawing() { 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()); ctx.request_paint_rect(e.bounding_box());
}); }
} else { } else {
ctx.request_paint(); ctx.request_paint();
} }