c# - WinForms - 如何在加载表单时使用 PaintEventArgs 运行函数?

标签 c# image winforms

我试图理解图形,在 Graphics.FromImage 文档中,它以这个为例:

private void FromImageImage(PaintEventArgs e)
{

    // Create image.
    Image imageFile = Image.FromFile("SampImag.jpg");

    // Create graphics object for alteration.
    Graphics newGraphics = Graphics.FromImage(imageFile);

    // Alter image.
    newGraphics.FillRectangle(new SolidBrush(Color.Black), 100, 50, 100, 100);

    // Draw image to screen.
    e.Graphics.DrawImage(imageFile, new PointF(0.0F, 0.0F));

    // Dispose of graphics object.
    newGraphics.Dispose();
}

我是 C# 和 Windows 窗体的新手,正在努力理解它们是如何组合在一起的。这段代码是如何运行的,比如说何时首次加载表单或何时按下按钮?

最佳答案

也许这会有所帮助。我有一个示例,既在 Paint 事件上绘制,也在现有的 Image 上绘制。我创建了一个带有两个图片框的表单。每个案例一个。 pictureBox1 有一个用于 .Paint 事件的事件处理程序,而 pictureBox2 仅在按下按钮时绘制。

form design

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        pictureBox1.BackColor=Color.Black;
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        // The code below will draw on the surface of pictureBox1
        // It gets triggered automatically by Windows, or by
        // calling .Invalidate() or .Refresh() on the picture box.
        DrawGraphics(e.Graphics, pictureBox1.ClientRectangle);
    }

    private void toolStripButton1_Click(object sender, EventArgs e)
    {
        // The code below will draw on an existing image shown in pictureBox2
        var img = new Bitmap(pictureBox2.Image);
        var g = Graphics.FromImage(img);

        DrawGraphics(g, pictureBox2.ClientRectangle);
        pictureBox2.Image=img;
    }

    void DrawGraphics(Graphics g, Rectangle target)
    {
        // draw a red rectangle around the moon 
        g.DrawRectangle(Pens.Red, 130, 69, 8, 8);
    }
}

因此,当您启动应用程序时,一个红色矩形仅出现在左侧,因为尚未按下该按钮。

before click

当按下按钮时,红色矩形出现在 pictureBox2 中显示的图像的顶部。

after click

没什么戏剧性的,但它完成了工作。因此,根据您需要的操作模式(用户图形或图像注释)使用示例代码来了解如何操作。

关于c# - WinForms - 如何在加载表单时使用 PaintEventArgs 运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55995225/

相关文章:

javascript - 从 Unity webGL 应用程序导出网格并将其与 AR.js 制作者关联

c# - 如何从 Amibroker 持续导出数据

mysql - Codeigniter 将多个图像插入数据库并根据唯一 ID 检索它们

python - 将一组图像分类

c# - 在winforms中获取文本框的自动完成下拉框的句柄

c# - Entity Framework 加载/保存数据

c# - 分部类中的表单控件属性

c# - 在 IIS7 中从 ASP.NET 调用非托管代码

javascript - 加载图片而不是链接?

c# - 使用 rhino mock 的 lambda 单元测试失败