[英]Draw rectangle on Panel C# Form
問題:如何在面板而不是窗體上繪制矩形。 這是我的代碼:
/*
* 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()){}
我只是不確定如何根據我的代碼實現這一點...
聽起來您還沒有掛上面板的繪畫事件:
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子類化,並在子類控件中實現繪圖行為。 同樣,這使控件對其自己的呈現負責。
有關用戶繪制控件的信息,請參見
http://msdn.microsoft.com/en-us/library/b818z6z6(v=vs.71).aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.