Hello, I decided to write my analogue of Paint as a practice (I paint on the Panel, “processing” the canvas through the BitMap map , also put a “stub” on the PaintBackground so that the cleaning of the canvas is not caused) and encountered a number of problems
1) For some reason, if you use Graphics.Clear (fill color) to create BitMap, the background is absent as such, although if you use a ready-made picture, then everything is fine.
2) I just can’t figure out how to draw the elements so that “it doesn’t draw the map in the map”, and that’s what happens to me if I understand everything correctly.
I ask for advice on changing the method of drawing or how to fix the higher problems ...
Code (removed all unnecessary, so as not to interfere):
class Canvas : Panel { //################################################################### //Имя объекта типа Canvas на форме - canvas //################################################################### protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); } protected override void OnPaintBackground(PaintEventArgs e) //"заглушка", если это так называется { } } //описание формы, на которой находится canvas public partial class MainForm : Form { private bool enableBrush; private PointF coordinate; private PaintMode mode; private Bitmap map; private Color colorBrush; public enum PaintMode { None, Line, Brush, Rect, Rectangle } public MainForm() { InitializeComponent(); mode = PaintMode.None; Graphics g = canvas.CreateGraphics(); g.Clear(Color.White); //не отображает map = new Bitmap(canvas.Width, canvas.Height, g); colorBrush = Color.Green; enableBrush = false; } private void canvas_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { coordinate = e.Location; //запоминает позицию курсора при нажатии для рисования enableBrush = true; } } private void canvas_MouseUp(object sender, MouseEventArgs e) { if(e.Button == MouseButtons.Left) { enableBrush = false; map = new Bitmap(canvas.Width,canvas.Height); canvas.DrawToBitmap(map, new Rectangle(new Point(), canvas.Size)); // "сейвлю" текущую карту в map(BitMap) } } public void canvas_Paint(object sender, PaintEventArgs e) { if (enableBrush) { switch (mode) { case PaintMode.None: break; case PaintMode.Line: e.Graphics.DrawLine(new Pen(colorBrush), coordinate, canvas.PointToClient(MousePosition)); break; case PaintMode.Brush: break; case PaintMode.Rect: break; case PaintMode.Rectangle: break; default: break; } } } private void canvas_MouseMove(object sender, MouseEventArgs e) { canvas.Invalidate(); //вызываю перерисовку в каждый момент времени, когда курсор мыши находится над canvas } private void LineButton_CheckedChanged(object sender, EventArgs e) { if (mode == PaintMode.Line) mode = PaintMode.None; else mode = PaintMode.Line; } }