在Panel C#Form上绘制矩形

时间:2011-11-07 23:35:16

标签: c# graphics panel

问题:如何在Panel上绘制矩形,而不是表单。这是我的代码:

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

我假设我需要做这样的事情:

使用(Graphics g = this.panel1.CreateGraphics()){}

我只是不确定如何在我的代码中实现这个......

2 个答案:

答案 0 :(得分:4)

听起来你还没有联系到小组的油漆事件:

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
}

答案 1 :(得分:1)

看起来父(form?)负责绘制每个控件。

我不这样做。

如果您只需要一个绘制形状的控件(并且不一定需要Panel的其他行为),我只需创建一个用户控件,该控件具有一个属性,指示要绘制的形状并使其负责自己的渲染

如果确实需要面板的行为,则可以继承Panel并在子类控件中实现绘图行为。同样,这使得控件负责自己的渲染。

有关用户绘制控件的信息,请参阅

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