如何在 C# 中绘制面板?

2024-04-04

嘿,我需要在 C# 中的面板上进行绘图,但没有将绘图代码放在“panel1_Paint”中,我该怎么做? 顺便说一句,我正在使用 WinForms。

Update:我忘了说清楚,我不需要将绘图代码放在绘图处理程序中,因为我需要根据按钮的事件开始绘图。


通常,您在绘制事件处理程序中完成所有绘图。如果您想要进行任何更新(例如,如果用户单击面板),则必须推迟该操作:存储所需的数据(用户单击的坐标)并强制重绘控件。这会导致绘制事件被触发,然后您可以在其中绘制之前存储的内容。

另一种方法是(如果您确实想在“panel1_Paint”事件处理程序之外进行绘制)在缓冲区图像内进行绘制,并将图像复制到绘制事件处理程序中的控件图形对象。

Update:

一个例子:

public class Form1 : Form
{
    private Bitmap buffer;

    public Form1()
    {
        InitializeComponent();

        // Initialize buffer
        panel1_Resize(this, null);
    }

    private void panel1_Resize(object sender, EventArgs e)
    {
        // Resize the buffer, if it is growing
        if (buffer == null || 
            buffer.Width < panel1.Width || 
            buffer.Height < panel1.Height)
        {
            Bitmap newBuffer = new Bitmap(panel1.Width, panel1.Height);
            if (buffer != null)
                using (Graphics bufferGrph = Graphics.FromImage(newBuffer))
                    bufferGrph.DrawImageUnscaled(buffer, Point.Empty);
            buffer = newBuffer;
        }
    }

    private void panel1_Paint(object sender, PaintEventArgs e)
    {
        // Draw the buffer into the panel
        e.Graphics.DrawImageUnscaled(buffer, Point.Empty);
    }



    private void button1_Click(object sender, EventArgs e)
    {
        // Draw into the buffer when button is clicked
        PaintBlueRectangle();
    }

    private void PaintBlueRectangle()
    {
        // Draw blue rectangle into the buffer
        using (Graphics bufferGrph = Graphics.FromImage(buffer))
        {
            bufferGrph.DrawRectangle(new Pen(Color.Blue, 1), 1, 1, 100, 100);
        }

        // Invalidate the panel. This will lead to a call of 'panel1_Paint'
        panel1.Invalidate();
    }
}

现在,即使在重绘控件之后,绘制的图像也不会丢失,因为它只绘制缓冲区(图像,保存在内存中)。此外,您可以在事件发生时随时绘制内容,只需绘制到缓冲区即可。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 C# 中绘制面板? 的相关文章

随机推荐