C#Graphics绘制任何对象

时间:2012-07-29 10:17:24

标签: c# generics graphics

我想在Windows窗体上绘制许多不同的形状。以下代码仅适用于矩形。

// 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);
    } 
}

如何改进代码以处理任何类型的形状,如矩形,直线,曲线等?

我想我需要一个可以包含不同类型对象的列表,以及根据其形状类型绘制任何对象的函数。但不幸的是我不知道该怎么做。

1 个答案:

答案 0 :(得分:4)

这样的事情:

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));
}

或者,您可以为要绘制的每种类型创建扩展方法。例如:

public static class ShapeExtensions
{
    public static void Draw(this Rectangle r, Graphics graphics)
    {
        graphics.FillRectangle(new SolidBrush(Color.Black), r);
    }
}