我有PictureBox
作为UserControl
。我在主表单上添加了User Control
。现在我必须按一个按钮并在用户控件上创建一行。在我的项目中,每次按下此按钮,我都要向用户发送两个PointF(x和y)的控制参数,并绘制一条新线,此外还有现有线。到目前为止,我已加载了图片框的Paint
事件。
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Pen graphPen = new Pen(Color.Red, 2);
PointF pt1D = new PointF();
PointF pt2D = new PointF();
pt1D.X = 0;
pt1D.Y = 10;
pt2D.X = 10;
pt2D.Y = 10;
e.Graphics.DrawLine(graphPen, pt1D, pt2D);
}
答案 0 :(得分:1)
假设您想在点击按钮时绘制线条,这是您的代码的修改版本:
List<PointF> points = new List<PointF>();
Pen graphPen = new Pen(Color.Red, 2);
private void btnDrawLines_Click(object sender, EventArgs e)
{
Graphics g = picBox.CreateGraphics();
PointF pt1D = new PointF();
PointF pt2D = new PointF();
pt1D.X = 0;
pt1D.Y = 10;
pt2D.X = 10;
pt2D.Y = 10;
g.DrawLine(graphPen, pt1D, pt2D);
points.Add(pt1D);
points.Add(pt2D);
}
private void picBox_Paint(object sender, PaintEventArgs e)
{
for (int i = 0; i < points.Count; i+=2)
e.Graphics.DrawLine(graphPen, points[i], points[i + 1]);
}
请注意,您可以通过PictureBox
类的CreateGraphics()
方法获取Graphics对象,该方法与e.Graphics
事件处理程序中的Paint
对象相同。
答案 1 :(得分:0)
如果要添加要绘制的线条,您可能需要一个小Line
类:
public class Line {
public Point Point1 { get; set; }
public Point Point2 { get; set; }
public Line(Point point1, Point point2) {
this.Point1 = point1;
this.Point2 = point2;
}
}
然后你可以将这些“行”添加到列表中:
private List<Line> _Lines = new List<Line>();
并添加它们并告诉控件更新它的绘图:
_Lines.Add(new Line(new Point(10, 10), new Point(42, 42)));
_Lines.Add(new Line(new Point(20, 40), new Point(20, 60)));
pictureBox1.Invalidate()
然后在你的图纸中:
private void pictureBox1_Paint(object sender, PaintEventArgs e) {
e.Graphics.Clear(Color.White);
foreach (Line l in _Lines) {
e.Graphics.DrawLine(Pens.Red, l.Point1, l.Point2);
}
}