2011-11-07 64 views
2

問題:如何在面板上繪製矩形,而不是在表單上繪製矩形。這裏是我的代碼如下所示:在面板C#上繪製矩形表格

/* 
    * based on a some flags i determine which shape i want to draw. 
    * All shapes are stored in a list. I loop through the list 
    * and call each shape specific draw method - as shown below:. 
    * 
    */ 
namespace myDrawProgram 
{ 
    private void panelArea_Paint(object sender, PaintEventArgs e) 
     { 
      if (drawWithPaint == true) 
      { 
       Pen p = new Pen(Color.Blue); 
       p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash; 

       if (IsShapeRectangle == true) 
       { 
        e.Graphics.DrawRectangle(p, rect); 
       } 
       else if (IsShapeCircle == true) 
       { 
        e.Graphics.DrawEllipse(p, rect); 
       } 

      } 
      foreach (Shapes shape in listOfShapes) 
      { 

       shape.Draw(e.Graphics); 
      } 
     } 
} 

/* 
* In another file i have my class which deals with 
* drawing rectangles. It is as follows: 
* 
*/ 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Drawing; 
using SETPaint; 

namespace myDrawProgram 
{ 
    class TheRectangles : Shapes 
    { 
     public Rectangle MyRect { set; get; } 

     public TheRectangles(Rectangle rect, Color colour, Color boarderColour, Int32 brushThickness) 
      : base(colour, boarderColour, brushThickness) 
     { 
      MyRect = rect; 

     } 


     public override void Draw(Graphics g) 
     { 
      base.Draw(g); 


      g.FillRectangle(new SolidBrush(Shapes.c), MyRect); 
      g.DrawRectangle(new Pen(bc, MyBrushThickness), MyRect); 
     } 
    } 
} 

我假設我需要做的是這樣的:使用

(圖形G = this.panel1.CreateGraphics()){}

我只是不知道如何實現這與我的代碼...

+0

你是說你想把你的面板類的繪圖邏輯,而不是在你的窗體?事實上,你的問題對我來說毫無意義。 –

+0

我不想在窗體上繪製矩形。我希望它在面板上顯示出來 - 目前,當我在面板上畫畫時,什麼也沒有顯示出來......這有道理嗎?希望如此.. – BigBug

+0

你看看這個:[http://stackoverflow.com/questions/282838/drawing-on-top-of-controls-inside-a-panel-c-winforms](http://stackoverflow .com/questions/282838/drawing-on-top-of-controls-inside-a-panel-c-winforms) – Udomaki

回答

4

聽起來好像你還沒有迷上了面板的Paint事件:

panelArea.Paint += new PaintEventHandler(panelArea_Paint); 

如果panelArea的名稱是你的形式,然後只需將其更改爲面板:

panel1.Paint += new PaintEventHandler(panel1_Paint); 

和ñ移動你的繪畫邏輯到該方法:

private void panel1_Paint(object sender, PaintEventArgs e) { 
    // the rest of your drawing 
} 
+0

謝謝。我現在知道了 – BigBug

1

它看起來像父(形式?)負責繪製其每個控件。

我不會那樣做。

如果您只需要一個繪製形狀的控件(並且不一定需要面板的其他行爲),那麼我只需創建一個用戶控件,該控件具有一個屬性,指示要繪製的形狀並使其對其自身負責渲染。

如果您確實需要某個面板的行爲,那麼可以繼承Panel並在您的子類控件中實現繪圖行爲。同樣,這使控制負責自己的渲染。

有關用戶繪製控件信息看

http://msdn.microsoft.com/en-us/library/b818z6z6(v=vs.71).aspx