C # GDI + simple Drawing (iv)

Source: Internet
Author: User
I have already introduced to you how to use GDI + to draw, and do an example, this article I introduce you how to do a similar Windows Paint tool.
Personally think that if you want to do a powerful drawing tool, then simply mastering GDI is far from enough, I can only do a relatively simple drawing tool now. Shortcomings, welcome to discuss!

Let's take a look at the final effect:








Main features: Draw straight lines, rectangles, erasers, circles, toggle colors, open pictures, save pictures, clear pictures, manually adjust the size of the canvas; When the software starts, it is a blank canvas, we can draw directly on the canvas, or through the menu "open", import a picture, Then we can draw on this picture.
Platform: VS2005 WINFORM



Because of the code too much, here is only a brief introduction of the next production steps, to provide you with engineering downloads.
1. Lay out the entire interface.
2. Implement the function of the drawing tool
3. To achieve the function of color pickup, here we directly take the last written custom control to use.
4. Implement Menu function
5. The ability to manually adjust the size of the canvas
6. Testing

Implementing the functionality of the drawing tool
In order to let the code of the small point, slightly with some design mode, because it is not very likely, so the code is a bit messy, hey! These functional blocks of the drawing tool are all written in the Drawtools class. In the main form, you just need to call this class to finish drawing, without having to involve too much specific drawing code. Drawing tools This class provides the main tools: Pencil, eraser, line, rectangle, circle, solid rectangle, solid circle. The code about these function blocks is not difficult, as long as we have carefully read the previous content, it should be able to read.
Here are some points to note:
1. How do I prevent the recording of unnecessary traces in the drawing process?
This question is mentioned in the third article, we might as well go to see that one first. To make the code seem high-readability, I set up two image variables, finishingimg used to save traces of the drawing process, orginalimg used to save the completed drawing process and the initial background image.
2. How does this class communicate with the main form?
Of course, if you write these function blocks directly in the main form, there is no problem. But that will make the code very messy, and if it's just a problem with the tool code, you need to change the whole project. I'm here. By defining methods and properties, let the main form pass information about the artboard canvas and color to the tool class by assigning a value to the property, and then use the tools by invoking the appropriate tool methods.
3. Key attributes
For these tools to work properly, you must pass to him the following things: the target artboard (i.e., PictureBox), the drawing color, the original canvas.

Implementing menu Functions






Here we need to understand the operation of the file, we can check the relevant information.
The main difficulty is to "open" the implementation of this menu item
We want to implement the open image after the change to save the file must be opened to shut down, or the file will be opened to overwrite the original file. Causes a "GDI generic error" to be ejected at compile time. So, according to other friends on the Internet, you can start by drawing an open picture onto another canvas with GDI +, and then close the open picture and the artboard you use to draw the picture.


private void openPic_Click (object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog (); // Instantiate the file open dialog
            ofd.Filter = "JPG | * .jpg | Bmp | * .bmp | All files | *. *"; // Set the open file name of the dialog box
            if (ofd.ShowDialog () == DialogResult.OK)
            {
                Bitmap bmpformfile = new Bitmap (ofd.FileName); // Get open file
                panel2.AutoScrollPosition = new Point (0,0); // Reset the scroll bar
                pbImg.Size = bmpformfile.Size; // Adjust the drawing area size to the picture size

                reSize.Location = new Point (bmpformfile.Width, bmpformfile.Height); // reSize is what I use to achieve manual adjustment of the canvas size
                // Because our initial blank canvas size is limited, the "open" operation may cause the size of the artboard to change.
                dt.DrawTools_Graphics = pbImg.CreateGraphics ();

                Bitmap bmp = new Bitmap (pbImg.Width, pbImg.Height);
                Graphics g = Graphics.FromImage (bmp);
                g.FillRectangle (new SolidBrush (pbImg.BackColor), new Rectangle (0, 0, pbImg.Width, pbImg.Height)); // Without using this sentence, the background of this bmp is transparent
                g.DrawImage (bmpformfile, 0, 0, bmpformfile.Width, bmpformfile.Height); // Draw the picture to the artboard
                g.Dispose (); // Release the resources occupied by the artboard
                // Do not use pbImg.Image = Image.FormFile (ofd.FileName) directly because this will keep the picture open, and you will not be able to save the modified picture
                bmpformfile.Dispose (); // Release the resources occupied by the picture
                g = pbImg.CreateGraphics ();
                g.DrawImage (bmp, 0, 0);
                g.Dispose ();
                dt.OrginalImg = bmp;
                bmp.Dispose ();
                sFileName = ofd.FileName; // Save the detailed path of the opened image file, which can be used to overwrite this file later
                ofd.Dispose ();

            }
        }


To clear the image is to fill the entire canvas with white
The rest is relatively simple, which is not specifically said.

Implementation Manually adjusting the canvas size
Someone on the web said that using the API, but it's easier for people to use other controls, at least we can understand.
Idea: Place a picturebox1 (size of 5*5), fixed it in the lower right corner of the main artboard, and then change the mouse to enter the cursor as the arrow shape, set the mouse to move the event, let the picturebox1 follow the mouse to move. When the mouse is released, the coordinates of the lower-right corner of the main artboard are adjusted to picturebox1 coordinates.
Here's the code:
The Resize is the PictureBox control we use to help


private bool bReSize = false; // whether to change the canvas size
        private void reSize_MouseDown (object sender, MouseEventArgs e)
        {
            bReSize = true; // When the mouse is pressed, it indicates that the size should be adjusted
        }

        private void reSize_MouseMove (object sender, MouseEventArgs e)
        {
            if (bReSize)
            {
                reSize.Location = new Point (reSize.Location.X + e.X, reSize.Location.Y + e.Y);

            }
        }

        private void reSize_MouseUp (object sender, MouseEventArgs e)
        {
            bReSize = false; // end of size change
            // Adjusting the size may cause the size of the artboard to exceed the screen area, so set autoScroll to true beforehand.
            // But the appearance of the scroll bar has increased our difficulty, because moving the scroll bar up and down does not automatically help us adjust the coordinates of the picture.
            // This is because there is more than one coordinate system for GDI drawing, there seem to be three, without careful understanding, one is screen coordinates, one is client area coordinates, and the other is document coordinates.
            // The up and down movement of the scroll bar changes the coordinates of the document, but the client area coordinates do not change, and the location property belongs to the client area coordinates, so we will directly calculate the error
            // At this time, we need to know the offset between the document coordinates and the client area coordinates. This is what AutoScrollPostion can provide

            pbImg.Size = new Size (reSize.Location.X-(this.panel2.AutoScrollPosition.X), reSize.Location.Y-(this.panel2.AutoScrollPosition.Y));
            dt.DrawTools_Graphics = pbImg.CreateGraphics (); // Because the size of the artboard has been changed, it must be re-assigned

            // In addition, the canvas has also been changed, so it must be reassigned.
            Bitmap bmp = new Bitmap (pbImg.Width, pbImg.Height);
            Graphics g = Graphics.FromImage (bmp);
            g.FillRectangle (new SolidBrush (Color.White), 0, 0, pbImg.Width, pbImg.Height);
            g.DrawImage (dt.OrginalImg, 0, 0);
            g.Dispose ();
            g = pbImg.CreateGraphics ();
            g.DrawImage (bmp, 0, 0);
            g.Dispose ();
            dt.OrginalImg = bmp;

            bmp.Dispose ();
        } 


Effects such as (look carefully at the lower right corner of the white area):






You can now resize the image by dragging that small square.
  
In this way, the major problems have been solved, but there are still inadequacies, and we welcome your valuable comments.





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.