C# 如何在图片框上绘制文字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/849359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to draw text on picturebox?
提问by Ivan Prodanov
I googled for "Drawing text on picturebox C#" ,but I couldnt find anything useful.Then I googled for "Drawing text on form C#" and I found some code,but it doesnt work the way I want it to work.
我用谷歌搜索“在图片框 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();
}
}
When I call the function,the background color of the form becomes white(it's black by default).
当我调用该函数时,表单的背景颜色变为白色(默认为黑色)。
My questions:
我的问题:
1:Will this work on a picturebox?
1:这可以在图片框上使用吗?
2:How to fix the problem?
2:如何解决问题?
采纳答案by Jon B
You don't want that call to Clear() - that's why it's turning the background white, and it will cover up your picture.
您不希望调用 Clear() - 这就是为什么它会将背景变成白色,并且会覆盖您的图片。
You want to use the Paint event in the PictureBox. You get the graphics reference from e.Graphics, and then use the DrawString() that you have in your sample.
您想在 PictureBox 中使用 Paint 事件。您可以从 e.Graphics 获取图形参考,然后使用示例中的 DrawString()。
Here's a sample. Just add a picture box to your form, and add an event handler for the Paint event:
这是一个示例。只需在表单中添加一个图片框,并为 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));
}
}
(Note that you won't see the text at design time - you'll have to run the program for it to paint).
(请注意,在设计时您不会看到文本 - 您必须运行该程序才能进行绘制)。