如何在图片框上绘制文字?

Iva*_*nov 14 c# graphics image

我用谷歌搜索"在图片框C#上绘图文字",但我找不到任何有用的东西.然后我用谷歌搜索"在C#上绘图文字",我发现了一些代码,但它并没有按照我希望的方式工作.

    private void DrawText()
    {
        Graphics grf = this.CreateGraphics();
        try
        {
            grf.Clear(Color.White);
            using (Font myFont = new Font("Arial", 14))
            {
                grf.DrawString("Hello .NET Guide!", myFont, Brushes.Green, new PointF(2, 2));
            }
        }
        finally
        {
            grf.Dispose();
        }
    }
Run Code Online (Sandbox Code Playgroud)

当我调用该函数时,表单的背景颜色变为白色(默认情况下为黑色).

我的问题:

1:这会在图片盒上工作吗?

2:如何解决问题?

Jon*_*n B 36

你不希望调用Clear() - 这就是为什么它将背景变为白色,它会掩盖你的照片.

您想在PictureBox中使用Paint事件.您可以从e.Graphics获取图形参考,然后使用样本中的DrawString().

这是一个样本.只需在表单中添加一个图片框,并为Paint事件添加一个事件处理程序:

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    using (Font myFont = new Font("Arial", 14))
    {
        e.Graphics.DrawString("Hello .NET Guide!", myFont, Brushes.Green, new Point(2, 2));
    }
}
Run Code Online (Sandbox Code Playgroud)

(请注意,您不会在设计时看到文本 - 您必须运行程序才能绘制).