【问题标题】:add multiple picturebox to a main Picturebox and draw them将多个图片框添加到主图片框并绘制它们
【发布时间】:2015-09-28 16:35:28
【问题描述】:

我有一个主要的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 内部处理那些 On Events,现在在主 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 失去焦点时,我看到了我的矢量,当我尝试再次绘制并失去焦点时没有任何反应..

为什么会出现这种奇怪的行为,我该如何解决?

【问题讨论】:

  • currentLayer 设置在哪里?
  • @PatrikEckebrecht 在 OnMouseClick event 里面,我打电话给 Invalidate() OnMouseMove event。

标签: c# winforms picturebox


【解决方案1】:

您忘记挂钩您的活动。

将这些行添加到您的课程中:

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 对象的设置。如果您需要在多个状态(可能是缩放或剪切、旋转或平移等)之间切换,这很有用。但这里不适用!

Graphics.Flush 刷新所有挂起的图形操作,但确实没有理由怀疑您的应用程序中有任何操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    相关资源
    最近更新 更多