canvas.rs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. use gdk;
  2. use gtk::{
  3. self,
  4. WidgetExt
  5. };
  6. use std::cell::RefCell;
  7. use std::rc::Rc;
  8. pub struct HexGridCanvas {
  9. pub canvas: gtk::DrawingArea,
  10. pub mouse_loc: Rc<RefCell<Option<(i32, i32)>>>,
  11. }
  12. impl HexGridCanvas {
  13. pub fn new() -> HexGridCanvas {
  14. let canvas = gtk::DrawingArea::new();
  15. let mouse_loc = Rc::new(RefCell::new(None));
  16. let reader_mouse = mouse_loc.clone();
  17. let writer_mouse = mouse_loc.clone();
  18. canvas.connect_draw(move |cv, ctx| {
  19. let w = cv.get_allocated_width();
  20. let h = cv.get_allocated_height();
  21. ctx.set_source_rgb(1.0, 1.0, 1.0);
  22. ctx.rectangle(0.0, 0.0, w as f64, h as f64);
  23. ctx.fill();
  24. ctx.set_source_rgb(0.9, 0.9, 0.9);
  25. reader_mouse.borrow().map(|(x, y)| {
  26. ctx.rectangle(x as f64 * 32.0, y as f64 * 32.0, 32.0, 32.0);
  27. ctx.fill();
  28. });
  29. ctx.set_source_rgb(0.8, 0.8, 0.8);
  30. for x in 0..((w / 32) + 1) {
  31. ctx.move_to(x as f64 * 32.0, 0.0);
  32. ctx.line_to(x as f64 * 32.0, h as f64);
  33. ctx.stroke();
  34. }
  35. for y in 0..((h / 32) + 1) {
  36. ctx.move_to(0.0, y as f64 * 32.0);
  37. ctx.line_to(w as f64, y as f64 * 32.0);
  38. ctx.stroke();
  39. }
  40. gtk::Inhibit(false)
  41. });
  42. canvas.connect_motion_notify_event(move |cv, motion| {
  43. let (x, y) = motion.get_position();
  44. *writer_mouse.borrow_mut() = Some((x as i32 / 32, y as i32 / 32));
  45. cv.queue_draw();
  46. gtk::Inhibit(false)
  47. });
  48. canvas.add_events(gdk::POINTER_MOTION_MASK.bits() as i32);
  49. HexGridCanvas {
  50. canvas,
  51. mouse_loc,
  52. }
  53. }
  54. }