2012-07-29 95 views
0

我想在Windows窗體上繪製許多不同的形狀。以下代碼僅適用於矩形。C#圖形繪製任何對象

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

如何才能提高代碼來處理任何類型的如矩形,直線,曲線的形狀,等等?

我想我需要一個列表,它可以包含不同類型的對象和函數,以根據其形狀類型繪製任何對象。但不幸的是,我不知道該怎麼做。

回答

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

+1 for oop idea – Ria 2012-07-29 10:27:22

+0

關於繪圖代碼是怎麼回事?我無法訪問那裏的圖形對象,是嗎? – danijar 2012-07-29 10:27:45

+0

@sharethis。您可以改變Draw方法以採取您認爲有必要的任何參數。 – 2012-07-29 10:29:47