将多个picturebox添加到主Picturebox并绘制它们

时间:2015-07-10 03:42:42

标签: 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, 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();
        }
    }

我正在主On Events内处理这些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失去焦点时,我会看到我的矢量,当我再次画画并失去焦点时,没有任何反应......

为什么这种奇怪的行为以及如何解决?

1 个答案:

答案 0 :(得分:0)

您忘记挂钩您的活动。

将这些行添加到您的班级:

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();
    }
}

Aslo这些行没用,应该删除:

    e.Graphics.Flush();
    e.Graphics.Save();

GraphicsState oldState = Graphics.Save将保存当前状态,即当前Graphics对象的设置。如果您需要在几种状态之间切换,可能是缩放或剪裁或旋转或翻译等,这很有用。但不是在这里!

Graphics.Flush刷新所有待处理的图形操作,但实际上没有理由怀疑你的应用程序中有任何操作。