在面板C#窗体上绘制矩形
问题:如何在面板上绘制矩形,而不是在窗体上绘制矩形。下面是我的代码的样子:在面板C#窗体上绘制矩形,c#,graphics,panel,C#,Graphics,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:. * */ names
/*
* 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()){}
我只是不知道如何在我的代码中实现这一点…看起来父级(表单?)负责绘制它的每个控件
我不会那样做的
如果您只需要一个绘制形状的控件(不一定需要面板的其他行为),我只需要创建一个用户控件,该控件具有一个属性,指示要绘制的形状,并使其负责自己的渲染
如果确实需要面板的行为,可以将面板子类化,并在子类化控件中实现绘图行为。同样,这使得控件负责自己的渲染
有关用户绘制控件的信息,请参见
听起来您还没有连接面板的喷漆事件:
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
}
您是说要将绘图逻辑放在panel类中,而不是放在窗体的?事实上,你的问题对我来说毫无意义。我不想在表格上画矩形。我希望它显示在面板上-目前,当我在面板上绘制时,没有显示任何内容。。。这有意义吗?希望如此。您看过这个了吗:您也可以使用pictureBox,因为您可以直接在控件上绘制图像……该事件处理程序是窗体的绘制事件还是面板的绘制事件?你确定有人叫它吗?