Reputation: 34225
I want to draw many different shapes on a Windows Form. The following code works only for rectangles.
// render list contains all shapes
List<Rectangle> DrawList = new List<Rectangle>();
// add example data
DrawList.Add(new Rectangle(10, 30, 10, 40));
DrawList.Add(new Rectangle(20, 10, 20, 10));
DrawList.Add(new Rectangle(10, 20, 30, 20));
// draw
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
foreach (Rectangle Object in DrawList)
{
g.FillRectangle(new SolidBrush(Color.Black), Object);
}
}
How can I improve the code to handle any type of shapes like rectangles, lines, curves, and so on?
I think I will need a list which can contain objects of different types and a function to draw any object depending on its type of shape. But unfortunately I have no idea how to do that.
Upvotes: 0
Views: 3598
Reputation: 24526
Something like this:
public abstract class MyShape
{
public abstract void Draw(PaintEventArgs args);
}
public class MyRectangle : MyShape
{
public int Height { get; set; }
public int Width { get;set; }
public int X { get; set; }
public int Y { get; set; }
public override void Draw(Graphics graphics)
{
graphics.FillRectangle(
new SolidBrush(Color.Black),
new Rectangle(X, Y, Width, Height));
}
}
public class MyCircle : MyShape
{
public int Radius { get; set; }
public int X { get; set; }
public int Y { get; set; }
public override void Draw(Graphics graphics)
{
/* drawing code here */
}
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
List<MyShape> toDraw = new List<MyShape>
{
new MyRectangle
{
Height = 10,
Width: 20,
X = 0,
Y = 0
},
new MyCircle
{
Radius = 5,
X = 5,
Y = 5
}
};
toDraw.ForEach(s => s.Draw(e.Graphics));
}
Alternatively, you could create an extension method for each type you wish to draw. Example:
public static class ShapeExtensions
{
public static void Draw(this Rectangle r, Graphics graphics)
{
graphics.FillRectangle(new SolidBrush(Color.Black), r);
}
}
Upvotes: 5