using Cairo; using Gdk; using Gtk; using Color = Cairo.Color; using Key = Gdk.Key; using static Gdk.EventMask; enum Tool {Line, Rectangle }; class Area : DrawingArea { Color red = new Color( 1 , 0, 0), white = new Color( 1 , 1, 1), green = new Color(0.5, 1,0.5, 0.5); ImageSurface surface; bool dragging = false; // не малюємо - кнопку миші не натиснуто double start_x, start_y; // початкові координати вказівника при пересуванні миші double end_x, end_y; // початкові координати вказівника при пересуванні миші public Tool tool = Tool.Line;// початковий інструмент - олівець для малювання ліній public Area() { surface = new ImageSurface(Format.Rgb24, 400, 400); using (Context c = new Context(surface)) { c.SetSourceColor(white); c.Paint(); } AddEvents((int) (ButtonPressMask | ButtonReleaseMask | PointerMotionMask)); } void draw(Context c) // молювання поточного об'єкта - відрізка чи прямокутника { c.SetSourceColor(red); c.LineWidth = 3; if (tool == Tool.Line) { c.MoveTo(start_x, start_y); c.LineTo(end_x, end_y); c.Stroke(); } else { c.Rectangle(x: start_x, y: start_y, width: end_x - start_x, height: end_y - start_y); c.StrokePreserve(); c.SetSourceColor(green); c.Fill(); } } protected override bool OnDrawn (Context c) { c.SetSourceSurface(surface, 0, 0); c.Paint(); if (dragging) draw(c); return true; } protected override bool OnButtonPressEvent (EventButton e) // При натисканні кнопки миші { dragging = true; (start_x, start_y) = (end_x, end_y) = (e.X, e.Y); QueueDraw(); return true; } protected override bool OnMotionNotifyEvent(EventMotion e) // При пересуванні миші з натиснутою кнопкою { if (dragging) { (end_x, end_y) = (e.X, e.Y); QueueDraw(); } return true; } protected override bool OnButtonReleaseEvent (EventButton e) // При вивільненні кнопки миші { dragging = false; using (Context c = new Context(surface)) draw(c); QueueDraw(); return true; } } class OwnWindow : Gtk.Window { Area area; public OwnWindow() : base("Малювання") { Resize(400, 400); area = new Area(); Add(area); } protected override bool OnKeyPressEvent (EventKey e) { switch (e.Key) // після натискання клавіші: { case Key.l: area.tool = Tool.Line; break;// l - малювати відрізок прямої case Key.r: area.tool = Tool.Rectangle; break;// r - малювати прямокутник } return true; } protected override bool OnDeleteEvent(Event e) { Application.Quit(); return true; } } class Example { static void Main() { Application.Init(); OwnWindow w = new OwnWindow(); w.ShowAll(); Application.Run(); } }