如何使用参数在Picturebox上动态绘制线条



我想通过传递参数来确定行的位置。

下面是我的代码。

private void Form1_Load(object sender, EventArgs e)
{
NormalVeiw = new PictureBox
{
Name = "NormalVeiw",
Size = new Size(100, 100),
Location = new Point(100, 100),
Visible = true,
};
Controls.Add(NormalVeiw);
size(0,0);
}
private void size(int p1, int p2)
{
Graphics g = NormalVeiw.CreateGraphics();
g.DrawLine(Pens.Red, new Point(p1, p2), new Point(100, 100));
g.Dispose();
}

有没有任何方法可以在没有PaintEventArgs e的情况下执行DrawLine?

using System.Drawing;
private Point p1, p2;
public Form2()
{
InitializeComponent();
p1 = new Point(0, 0);
p2 = new Point(150, 150);
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Rectangle rect = new Rectangle(e.ClipRectangle.X, e.ClipRectangle.Y, e.ClipRectangle.Width, e.ClipRectangle.Height);
e.Graphics.DrawRectangle(new Pen(Color.Green, 20), rect);
e.Graphics.DrawLine(new Pen(Color.Red), p1,p2);
}

最简单的情况是将x,y值移到表单级别,这样就可以从绘制事件中访问它们:

private int? p1, p2;
PictureBox NormalVeiw;        
private void Form1_Load(object sender, EventArgs e)
{
NormalVeiw = new PictureBox
{
Name = "NormalVeiw",
Size = new Size(100, 100),
Location = new Point(100, 100),
Visible = true,
};
NormalVeiw.Paint += (s, pe) => {
if (p1.HasValue && p2.HasValue)
{
pe.Graphics.DrawLine(Pens.Red, new Point(p1.Value, p2.Value), new Point(100, 100));
}                
};
Controls.Add(NormalVeiw);
size(0, 0);
}

您的size()方法将简单地更新那些x,y值,并更新Invalidate()图片框,使其重新绘制自己:

private void size(int p1, int p2)
{
this.p1 = p1;
this.p2 = p2;
NormalVeiw.Invalidate();
}

现在,您可以用不同的值调用size(),并且该行将发生更改。

如果需要多行,请创建某种结构/类来表示该行的信息,然后将其存储在List<YourStructureHere>中。在paint事件中,您将遍历该列表并绘制每一行。

最新更新