You do not need to serialize the panel, the panel is not serializable. You can consider any of these options:
- , . , . .
- , . . , , Visio.
:
: , , .
: , , , Save Load, . , , hit-testing moving shape. xml .
, .
Paint , DrawToBitmap :
private void button1_Click(object sender, EventArgs e)
{
using (var bm = new Bitmap(panel1.Width, panel1.Height))
{
panel1.DrawToBitmap(bm, new Rectangle(0, 0, bm.Width, bm.Height));
bm.Save(@"d:\panel.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
}
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.FillRectangle(Brushes.Red, 0, 0, 100, 100);
e.Graphics.FillRectangle(Brushes.Blue, 50, 50, 100, 100);
}
, LineShape RectangleShape, Shape. , :
[Serializable]
public abstract class Shape
{
public abstract void Draw(Graphics g);
public override string ToString() { return GetType().Name; }
}
[Serializable]
public class LineShape : Shape
{
public LineShape(){ Color = Color.Blue; Width = 2; }
public Point Point1 { get; set; }
public Point Point2 { get; set; }
public int Width { get; set; }
public Color Color { get; set; }
public override void Draw(Graphics g)
{
using (var pen = new Pen(Color, Width))
g.DrawLine(pen, Point1, Point2);
}
}
[Serializable]
public class RectangleShape : Shape
{
public RectangleShape() { Color = Color.Red; }
public Rectangle Rectangle { get; set; }
public Color Color { get; set; }
public override void Draw(Graphics g)
{
using (var brush = new SolidBrush(Color))
g.FillRectangle(brush, Rectangle);
}
}
ShapesList . :
[Serializable]
public class ShapesList : List<Shape>
{
public void Save(string file)
{
using (Stream stream = File.Open(file, FileMode.Create))
{
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(stream, this);
}
}
public void Load(string file)
{
using (Stream stream = File.Open(file, FileMode.Open))
{
BinaryFormatter bin = new BinaryFormatter();
var shapes = (ShapesList)bin.Deserialize(stream);
this.Clear();
this.AddRange(shapes);
}
}
public void Draw(Graphics g)
{
this.ForEach(x => x.Draw(g));
}
}
:
ShapesList Shapes;
private void Form3_Load(object sender, EventArgs e)
{
Shapes = new ShapesList();
Shapes.Add(new RectangleShape() { Rectangle = new Rectangle(0, 0, 100, 100),
Color = Color.Green });
Shapes.Add(new RectangleShape() { Rectangle = new Rectangle(50, 50, 100, 100),
Color = Color.Blue });
Shapes.Add(new LineShape() { Point1 = new Point(0, 0), Point2 = new Point(150, 150),
Color = Color.Red });
this.panel1.Invalidate();
}
private void button1_Click(object sender, EventArgs e)
{
Shapes.Save(@"d:\shapes.bin");
Shapes.Clear();
this.panel1.Invalidate();
MessageBox.Show("Shapes saved successfully.");
Shapes.Load(@"d:\shapes.bin");
this.panel1.Invalidate();
MessageBox.Show("Shapes loaded successfully.");
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
Shapes.Draw(e.Graphics);
}