所以這應該很簡單,但我已經看過一些類似的問題,找不到答案。從Panel_Paint中調用另一個類的方法不會繪製任何東西
我有Form1
類和Resistor
類。在Form1
類中,我有一個Panel
(我將名稱更改爲Canvas
),在Canvas_Paint
方法中,我從Resistor
類調用方法Draw
,但沒有畫任何東西。
Form1類:
public partial class Form1 : Form
{
static float lineWidth = 2.0F;
static float backgroundLineWidth = 2.0F;
static Pen pen = new Pen(Color.Yellow, lineWidth);
static Pen backgroundPen = new Pen(Color.LightGray, backgroundLineWidth);
private bool drawBackground = true;
private List<Resistor> resistors = new List<Resistor>();
public Form1()
{
InitializeComponent();
}
private void Canvas_Paint(object sender, PaintEventArgs e)
{
if (drawBackground)
{
Console.WriteLine("Drawing background...");
Draw_Background(e.Graphics, backgroundPen);
}
if (resistors != null)
{
foreach (Resistor r in resistors)
{
//This does not work.
r.Draw(e.Graphics);
}
}
//The line below draws the line fine.
e.Graphics.DrawLine(pen, 0, 0, 100, 100);
}
private void Draw_Background(Graphics g, Pen pen)
{
for (int i = 0; i < Canvas.Width; i += 10)
{
g.DrawLine(pen, new Point(i, 0), new Point(i, Canvas.Height));
}
for (int j = 0; j < Canvas.Height; j += 10)
{
g.DrawLine(pen, new Point(0, j), new Point(Canvas.Width, j));
}
drawBackground = false;
}
private void AddResistor_Click(object sender, EventArgs e)
{
resistors.Add(new Resistor());
Console.WriteLine("Added a Resistor...");
}
}
電阻類別:
public class Resistor
{
static private Point startingPoint;
static Pen defaultPen;
private Point[] points;
public Resistor()
{
startingPoint.X = 100;
startingPoint.Y = 100;
defaultPen = new Pen(Color.Yellow, 2.0F);
points = new Point[] {
new Point(10, 10),
new Point(10, 100),
new Point(200, 50),
new Point(250, 300)
};
}
public void Draw(Graphics g)
{
//Is this drawing somewhere else?
g.DrawLines(defaultPen, points);
}
}
我已經搜索這question這表明在這種情況下,通過e.Graphics
對象到Draw
方法在Resistor
類,但是不工作。
我是C#的新手,所以我非常感謝任何幫助。
編輯: 如果你想下載並試用它,我把項目放在github上。
編輯: 所以問題是,點擊按鈕後,面板漆方法沒有被調用。解決的辦法是添加Canvas.Invalidate
的AddResistor_Click
方法
您應該總是在'Paint'事件處理程序中使用'e.Graphics'。不惜一切代價避免'CreateGraphics';它不會像你期望的那樣工作。 –
他也忘記訂閱Paint事件。 –
@CodyGray謝謝你,我將它改爲'e.Graphics'。 – 0gravity