C# 将多个picturebox添加到主picturebox并绘制它们
我有一个主C# 将多个picturebox添加到主picturebox并绘制它们,c#,winforms,picturebox,C#,Winforms,Picturebox,我有一个主PictureBox,其中添加了一个其他图片框;我将父对象传递给子对象,并将其添加到父对象,如下所示: public class VectorLayer : PictureBox { Point start, end; Pen pen; public VectorLayer(Control parent) { pen = new Pen(Color.FromArgb(255, 0, 0,
PictureBox
,其中添加了一个其他图片框;我将父对象传递给子对象,并将其添加到父对象,如下所示:
public class VectorLayer : PictureBox
{
Point start, end;
Pen pen;
public VectorLayer(Control parent)
{
pen = new Pen(Color.FromArgb(255, 0, 0, 255), 8);
pen.StartCap = LineCap.ArrowAnchor;
pen.EndCap = LineCap.RoundAnchor;
parent.Controls.Add(this);
BackColor = Color.Transparent;
Location = new Point(0, 0);
}
public void OnPaint(object sender, PaintEventArgs e)
{
e.Graphics.DrawLine(pen, end, start);
}
public void OnMouseDown(object sender, MouseEventArgs e)
{
start = e.Location;
}
public void OnMouseMove(object sender, MouseEventArgs e)
{
end = e.Location;
Invalidate();
}
public void OnMouseUp(object sender, MouseEventArgs e)
{
end = e.Location;
Invalidate();
}
}
我从主PictureBox
中处理事件中的,现在在主PictureBox中处理Paint
事件,如下所示:
private void PicBox_Paint(object sender, PaintEventArgs e)
{
//current layer is now an instance of `VectorLayer` which is a child of this main picturebox
if (currentLayer != null)
{
currentLayer.OnPaint(this, e);
}
e.Graphics.Flush();
e.Graphics.Save();
}
但是当我什么都不画的时候,当我做了Alt+Tab
失去焦点的时候,我看到了我的向量,当我再次尝试画图,失去焦点的时候,什么都没有发生
为什么会出现这种奇怪的行为?我该如何解决它?您忘记了将您的活动连接起来
将以下行添加到类中:
MouseDown += OnMouseDown;
MouseMove += OnMouseMove;
MouseUp += OnMouseUp;
Paint += OnPaint;
不确定您是否不想在MouseMove
:
public void OnMouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
end = e.Location;
Invalidate();
}
}
此外,这些管线是无用的,应拆除:
e.Graphics.Flush();
e.Graphics.Save();
GraphicsState oldState=Graphics.Save
将保存当前状态,即当前图形对象的设置。如果需要在多个状态之间切换,可能需要缩放、剪裁、旋转或平移等,则此选项非常有用。。但不是在这里
Graphics.Flush
刷新所有挂起的图形操作,但是没有理由怀疑您的应用程序中有任何图形操作。currentLayer
设置在哪里?@PatrikEckebrecht-insideOnMouseClick
事件,我调用Invalidate()
OnMouseMove
事件。