将窗口从绘图捕获到图像 C# 时出现问题
本文关键字:问题 图像 窗口 绘图 | 更新日期: 2023-09-27 18:31:31
我正在尝试将一些对象绘制到Windows窗体,然后创建该窗体的图像并将其保存到文件夹中。
这是一个由两部分组成的问题...为什么正在绘制到窗口窗体的图像没有显示在创建的图像上?第二个问题是,我如何在没有背景的情况下创建窗口表单绘图的图像,从点 0,0 到点 500,500......
这是我目前拥有的代码....
Form draw = new Drawing(); // Opens the drawing form
draw.Show();
try
{
//Try to draw something...
System.Drawing.Pen myPen;
myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
System.Drawing.Graphics formGraphics = draw.CreateGraphics();
formGraphics.DrawLine(myPen, 0, 0, 500, 500);
myPen.Dispose();
formGraphics.Dispose();
var path = this.outputFolder.Text; // Create variable with output path
if (!Directory.Exists(path))
{
DirectoryInfo di = Directory.CreateDirectory(path); // Create path if it doesn't exist
}
using (var bitmap = new Bitmap(draw.Width, draw.Height)) // Creating the .bmp file from windows form
{
draw.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
bitmap.Save(path + "''" + i + ".bmp");
}
}
catch { }
你能看出这里有什么不对劲吗?什么似乎禁止将图形保存到.bmp文件中?
提前感谢!
我最终使用了此处显示的示例将System.Drawing.Graphics保存到png或bmp
Form draw = new Drawing(); // Opens the drawing form
draw.Show();
try
{
var path = this.outputFolder.Text; // Path where images will be saved to
if (!Directory.Exists(path))
{
DirectoryInfo di = Directory.CreateDirectory(path); // Create a directory if it does not already exist
}
Bitmap bitmap = new Bitmap(Convert.ToInt32(1024), Convert.ToInt32(1024), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmap);
System.Drawing.Pen myPen;
myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
g.DrawLine(myPen, 0, 0, 1024, 1024);
bitmap.Save(path + "''" + i + ".png", ImageFormat.Png);
}
catch { }
现在对我来说,这已经完美无缺地工作了:D