2012-07-29 2 views
0

Windows Form에 여러 가지 모양을 그려야합니다. 다음 코드는 직사각형에서만 작동합니다.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 oop idea – Ria

+0

그림 코드는 무엇입니까? 거기에 그래픽 객체에 액세스 할 수 없습니까? – danijar

+0

@sharethis. 필요한 것으로 간주되는 매개 변수를 취하도록 Draw 메서드를 변경할 수 있습니다. –

관련 문제