简体   繁体   中英

Issue capturing windows form drawing to image C#

I'm trying to draw a few objects to a windows form, then create a image of that form and save it to a folder.

This is a two part question... Why isn't the image that is being drawn to the windows form showing up on the created image? Also second question is, how can I create an image of the windows form drawing, from say point 0,0 to point 500,500 without a background....

Here is the code I have at the moment....

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 { }

Can you see anything wrong here? What seems to be prohibiting the drawings to be saved to a .bmp file?

Thank in advance!

I ended up using the example shown here Saving System.Drawing.Graphics to a png or 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 { }

And that has worked flawlessly for me now :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM