【问题标题】:Drawing on PictureBox在 PictureBox 上绘图
【发布时间】:2012-07-17 08:30:54
【问题描述】:

UserControl 中,我有一个PictureBox 和其他一些控件。对于包含这个名为Graph 的图片框的用户控件,我有一个在这个图片框上绘制曲线的方法:

    //Method to draw X and Y axis on the graph
    private bool DrawAxis(PaintEventArgs e)
    {
        var g = e.Graphics;
        g.DrawLine(_penAxisMain, (float)(Graph.Bounds.Width / 2), 0, (float)(Graph.Bounds.Width / 2), (float)Bounds.Height);
        g.DrawLine(_penAxisMain, 0, (float)(Graph.Bounds.Height / 2), Graph.Bounds.Width, (float)(Graph.Bounds.Height / 2));

        return true;
    }

    //Painting the Graph
    private void Graph_Paint(object sender, PaintEventArgs e)
    {
        base.OnPaint(e);
        DrawAxis(e);
     }

    //Public method to draw curve on picturebox
    public void DrawData(PointF[] points)
    {
        var bmp = Graph.Image;
        var g = Graphics.FromImage(bmp);

        g.DrawCurve(_penAxisMain, points);

        Graph.Image = bmp;
        g.Dispose();
    }

当应用程序启动时,轴被绘制。但是当我调用DrawData 方法时,我得到一个异常,说bmp 为空。可能是什么问题?

我还希望能够在用户单击某些按钮时多次调用DrawData 以显示多条曲线。实现这一目标的最佳方法是什么?

谢谢

【问题讨论】:

    标签: c# winforms drawing picturebox


    【解决方案1】:

    你从来没有分配过Image,对吧?如果您想在PictureBox' 图像上绘图,您需要先创建此图像,方法是为其分配一个具有 PictureBox 尺寸的位图:

    Graph.Image = new System.Drawing.Bitmap(Graph.Width, Graph.Height);
    

    您只需要这样做一次,如果您想重新绘制那里的任何内容,则可以重复使用该图像。

    然后您可以随后使用此图像进行绘图。欲了解更多信息,refer to the documentation

    顺便说一句,这完全独立于在Paint 事件处理程序中绘制PictureBox。后者直接在控件上绘制,而Image 用作自动绘制在控件上的后缓冲区(但您确实需要在绘制后调用Invalidate 来触发重绘后缓冲区)。

    此外,在绘制后将位图重新分配给PictureBox.Image 属性是有意义的。操作毫无意义。

    另外,由于Graphics 对象是一次性的,您应该将它放在using 块中,而不是手动处理它。这保证了在遇到异常时正确处理:

    public void DrawData(PointF[] points)
    {
        var bmp = Graph.Image;
        using(var g = Graphics.FromImage(bmp)) {
            // Probably necessary for you:
            g.Clear();
            g.DrawCurve(_penAxisMain, points);
        }
    
        Graph.Invalidate(); // Trigger redraw of the control.
    }
    

    您应该将其视为固定模式。

    【讨论】:

    • 不,我没有指定,我认为在图形上调用 Paint 方法会生成图像。你能解释一下如何解决这个问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    • 2012-05-10
    • 2018-03-16
    • 2011-11-13
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多