C #. Net Frame plotting Technology for Windows Forms

Source: Internet
Author: User
C #. Net Frame plotting Technology for Windows Forms

From: http://hi.baidu.com/ysdonet/blog/item/823fd655a9f9ffc1b745ae91.html

When writing a typical Windows form program,Drawing forms and controls, Effect and other operations do not need to be taken into consideration. Why? Because. NetFramework, developers can drag a series of controls to the form, write some simple code associated with the event, and then press F5 In the IDE, a complete Form program is born! All controls draw their own, and the size and scaling of the form or control can be adjusted freely. It is often used here, and the control effect should be noted. For games, custom chart controls, and Screen Saver Programming, the programmer needs to write additional code to respond to the paint event.

This article targets those windows forms developers and helps them use simple plotting techniques during application preparation. First, we will discuss some basic plotting concepts. Who is responsible for drawing? How does a Windows form program know when to draw? Where exactly are the drawing codes placed? Next, we will introduce the dual Buffer technology for Image Rendering. You will see how it works and how to use a method to achieve the alternation between the cache and the actually displayed image. Finally, we will discuss "smart invalid areas". Actually, we just re-paint or clear invalid parts of the application form to speed up the display and response of the program. We hope that these concepts and technologies will guide readers through this article and help them develop Windows Forms programs more quickly and effectively.

Windows Forms use the GDI + Image Engine. All the drawing code in this article involves using the managed. NET Framework to manipulate and use the Windows GDI + Image Engine.

Although this article is used for basic form drawing operations, it also provides fast, effective techniques and methods that help improve program performance. Therefore, before reading this article, we recommend that you have a basic understanding of the. NET Framework, including windows form event processing, simple GDI + objects such as line, pen, and brush. Familiar with Visual Basic. Net or C # programming language.

  Concept

Windows applications are drawn by themselves. When a form is "not clean", that is, the size of the form is changed, or some of the forms are overwritten by other programs, or restored from the minimized state, the program will receive the information to be drawn. In Windows, this "not clean" status is called "invalid (invalidated)". We understand that re-painting is required, when the Windows form program needs to redraw the form, it obtains the drawn information from the Windows message queue. This information is encapsulated by the. NET Framework and then transmitted to the paintbackground and painting events of the form. In the above events, you can properly write the code specifically for drawing.

A simple drawing example is as follows:

The following is a reference clip:
Using system;
Using system. drawing;
Using system. Windows. forms;
Public class basicx: Form
{
Public basicx ()
{
Initializecomponent ();
}
Private void basicx_paint (Object sender, painteventargs E)
{
Graphics G = E. graphics;
Pen P = new pen (color. Red );
Int width = clientrectangle. width;
Int Height = clientrectangle. height;
G. drawline (p, 0, 0, width, height );
G. drawline (p, 0, height, width, 0 );
P. Dispose ();
}
Private void initializecomponent ()
{
This. setstyle (controlstyles. resizeredraw, true );
This. clientsize = new system. Drawing. Size (300,300 );
This. Text = "basicx ";
This. Paint + = new painteventhandler (this. basicx_paint );
}
[System. stathreadattribute ()]
Public static void main ()
{
Application. Run (New basicx ());
}
}

The above code is divided into two basic steps to create a sample program. First, the initializecomponent method contains some attribute settings and the processing process of adding a form paint event. Note that the style of the control is also set in the method. Setting the style of the control is also an effective way to customize Windows Forms and control behaviors. For example: the "resizeredraw" attribute of the control indicates that the form must be completely re-painted when the size of the form changes. That is to say, the customer area of the entire form must always be re-painted. The "customer region" of a form refers to all the form regions except the title bar and border. You can perform an interesting experiment to cancel the property of the control and then run the program. We can clearly see why this property is often set, because the invalid area after the form size is adjusted is not repainted at all.

Well, we need to pay attention to the basicx_paint method. As mentioned earlier, the paint event is activated when the program needs to be repainted, the program form uses the paint event to respond to the system message to be repainted. The basicx_paint method call requires an object sender and a painteventargs type variable, the painteventargs class instance or variable e encapsulates two important data. The first is the graphics object of the form, this object indicates the surface of a form that can be drawn, also known as a canvas, used to draw lines, text, and images. The second data is cliprectangle. This rectangle object indicates an invalid rectangular range on the form, that is, the area where the form needs to be repainted. Remember, after the resizereddraw of the form is set, the size of the cliprectangle is equal to the size of the entire customer area of the form, or the part of the cut area covered by other program forms. We will describe the usefulness of some cut areas in more detail in the intelligent re-painting chapter.

  Double buffer plot Technology

The dual-buffer technology allows the program to draw more quickly and smoothly, effectively reducing the image flickering during painting. The basic principle of this technology is to first draw an image to a canvas in the memory. Once all the painting operations are completed, push the canvas in the memory to the form or control surface to display it. After this operation, the program can make the user feel faster and more beautiful.

The example program provided below can clarify the concept and implementation method of dual buffer. This example has complete functions and can be used in practical applications. Later in this chapter, we will also mention that this technology should work with some property settings of controls to achieve better results.

Run the spiderweb sample program to learn the benefits of the dual-buffer plot technology. After the program starts and runs, adjust the window size. You will find that the efficiency of using this drawing algorithm is not high, and a large amount of flashes appear during the resizing process.

  Spiderweb sample programs without dual Buffer technology

Looking at the source code of the program, you will find that after the program paint event is activated, the line is drawn by calling the linedrawroutine method. The linedrawroutine method has two parameters. The first is that the graphics object is used to draw lines, and the second is the pen object of the drawing tool used to draw lines. The code is quite simple, a loop statement, linefreq constant, etc. The program is underlined from the lower left of the form surface to the upper right. Please note that the program uses floating point numbers to calculate the drawing position on the form. The advantage of this is that when the size of the form changes, the location data will be more accurate.

The following is a reference clip:
Private void linedrawroutine (Graphics g, pen P)
{
Float width = clientrectangle. width;
Float Height = clientrectangle. height;
Float xdelta = width/linefreq;
Float ydelta = height/linefreq;
For (INT I = 0; I <linefreq; I ++)
{
G. drawline (p, 0, height-(ydelta * I), xdelta * I, 0 );
}
}

Write a simple code for responding to the paint event spiderweb_paint. As mentioned earlier, the graphics object is the drawing surface of the form extracted from the painteventargs object of the paint event parameter. This graphics object is passed together with the newly created pen object to the linedrawroutine method to draw a line like a spider. The resources occupied by the graphics object and the pen object are released after the graphics object and the pen object are used, then the entire painting operation is complete.

The following is a reference clip:
Private void spiderweb_paint (Object sender, painteventargs E)
{
Graphics G = E. graphics;
Pen redpen = new pen (color. Red );
Linedrawroutine (G, redpen );
Redpen. Dispose ();
G. Dispose ();
}

So what changes can be made to implement a simple dual Buffer technology for the spiderweb program above? In fact, the principle is quite simple, that is, the painting operation that should be painted on the form surface should be converted to the bitmap in the memory first, and linedrawroutine will execute the same spider network Painting Operation to the canvas hidden in the memory, call graphics after drawing. the drawimage method pushes the hidden content on the canvas to the surface of the form for display. Finally, a high-performance drawing form program is completed with some minor changes.

Compare the differences between the following dual-buffer plot events and the simple plot events described above:

The following is a reference clip:
Private void spiderweb_dblbuff_paint (Object sender, painteventargs E)
{
Graphics G = E. graphics;
Pen bluepen = new pen (color. Blue );
Bitmap localbitmap = new Bitmap (clientrectangle. Width, clientrectangle. Height );
Graphics bitmapgraphics = graphics. fromimage (localbitmap );
Linedrawroutine (bitmapgraphics, bluepen );
// Pushes bitmap processed in memory to the foreground and displays
G. drawimage (localbitmap, 0, 0 );
Bitmapgraphics. Dispose ();
Bluepen. Dispose ();
Localbitmap. Dispose ();
G. Dispose ();
}

The above Sample Code creates a memory bitmap object, which is equal to the size of the form's customer region (that is, the drawing surface) by calling graphics. fromimage transfers the reference of the bitmap in the memory to the graphics object. That is to say, all subsequent operations on the graphics object are actually performed on the bitmap in the memory, this operation is equivalent to copying the pointer of a bitmap object to a graphics object in C ++. The two objects use the same memory address. The graphics object represents a canvas at the back of the screen, which plays a crucial role in the dual Buffer technology. All line drawing operations are targeted at bitmap objects in the memory. Next, call the drawimage method to copy the bitmap to the form, the lines of the spider web are immediately displayed on the drawing surface of the form without blinking.

This series of operations is not particularly effective after completion, because we first premise that the style of the control is also a way to define the behavior of the Windows form program, to better implement dual buffer, you must set the opaque attribute of the Control. This attribute indicates that the form is not responsible for drawing its own in the background. In other words, if this attribute is set, you must add the relevant code for the clear and redraw operations. Spiderweb programs with dual-buffer versions use the above settings to perform well when re-painting is required. The form surface is cleared with its own background color, which reduces the appearance of flashes.

The following is a reference clip:
Public spiderweb_dblbuff ()
{
Setstyle (controlstyles. resizeredraw | controlstyles. opaque, true );
}
Private void spiderweb_dblbuff_paint (Object sender, painteventargs E)
{
Bitmap localbitmap = new Bitmap (clientrectangle. Width,
Clientrectangle. Height );
Graphics bitmapgraphics = graphics. fromimage (localbitmap );
Bitmapgraphics. Clear (backcolor );
Linedrawroutine (bitmapgraphics, bluepen );
}

What are the results? Image Rendering is much smoother. From the memory, we pushed the spider's lines to the front end to show that there was no blinking at all, but we paused a little while, first trim the bitmap in the memory and then display it, you can add a line of code to make the line look flat.

The following is a reference clip:
Bitmapgraphics. smoothingmode = smoothingmode. antialias;

After assigning the bitmap object in the memory to graphics, we place this line of code. Every line we draw on the canvas uses anti-aliasing to make the uneven lines more flat.

Spiderweb_dblbuff sample programs that have dual Buffer technology and use the Antialiasing attribute

After a simple dual-buffer application is completed, there are two issues that need to be clarified to the reader. Some controls in. net, such as button, picturebox, label, and propertygrid, have made good use of this technology! By default, these controls automatically enable the dual Buffer technology. You can set the "doublebuffer" attribute to implement the dual Buffer technology. Therefore, if you use picturebox to draw spider web, it will be more efficient and make the program easier.

The dual-buffer technology we discuss here is neither completely optimized, but has no negative impact. Dual Buffer technology is an important way to reduce the flash of Windows Forms during painting, but it does consume a lot of memory because it will use double memory space: the image displayed by the application and the image in memory at the rear of the screen. Each time a paint event is activated, bitmap objects are dynamically created, which consumes a lot of memory. The control with the dual Buffer technology performs better after the doublebuffer attribute is used.

The Dib (device-independent Bitmap) object of GDI + is used to implement memory buffering outside the image. controls with a dual buffer mechanism can make good use of this bitmap object. DiB is the underlying Win32 object for efficient screen painting. Similarly, it is worth noting that the first version of GDI + is only related to hardware acceleration and some simple functions can be used directly. Due to such restrictions, screen rendering methods, such as anti-sawtooth and translucent, are executed quite slowly. Although the dual buffer mechanism consumes some memory, its use undoubtedly enhances the execution performance of the program.

  Intelligent re-painting, you need to consider before drawing

"Smart reuse" means that programmers should understand that only the invalid areas in the program should be repainted, repainting the invalid regions corresponding to the regions object can improve the rendering performance. By using the regions object, you can exclude or draw only some areas of the control and form to achieve better performance. Let's take a look at the basicclip sample program. This program uses the cliprectangle object stored in the painteventargs object, which we mentioned earlier, the paint event is activated whenever the program size changes. The basicclip example program fills the cut rectangular area with red and blue colors. After adjusting the size of the form several times with different speeds, you will find that the drawn rectangular area is actually an invalid area of the form (including the area greater than the size of the original form and the area smaller). The example program's paint Event code is as follows:

The following is a reference clip:
Private void basicclip_paint (Object sender, painteventargs E)
{
Graphics G = E. graphics;
If (currentbrush. Color = color. Red)
Currentbrush. Color = color. blue;
Else
Currentbrush. Color = color. Red;
G. fillrectangle (currentbrush, E. cliprectangle );
G. Dispose ();
}

The sole purpose of this example is to demonstrate how to draw images only for some areas.

The color rectangle area in the basicclip example program is the invalid area at the bottom and right of the form.

Regions is an object used to define windows forms or control areas. regions obtained after the form size is adjusted is the smallest area of the window weight painting. When the program needs to draw only the special areas of interest, so that drawing a smaller area will make the program run faster.

To better demonstrate regions usage, see the textcliping sample program. This program reloads the onpaintbackground and onpaint methods, and directly reloads these methods to ensure that the Code is called before other painting operations, and the rendering of custom controls is more effective. For clarity, the sample program provides a setup method that defines a global graphics object.

The following is a reference clip:
Private void setup ()
{
Graphicspath textpath = new graphicspath ();
Textpath. addstring (displaystring, fontfamily. genericserif,
0, 75, new point (10, 50), new stringformat ());
Textregion = new region (textpath );
Backgroundbrush = new texturebrush (New Bitmap ("coffeebeansmall.jpg "),
Wrapmode. tile );
Foregroundbrush = new solidbrush (color. Red );
}

The setup method above first defines an empty graphicspath object variable textpath. The next line of the string "Windows Forms" is added to this path and a region is created around this outline. In this way, a region that is drawn on the surface of the form in the string contour area is created. Finally, the setup method creates a form with the material brush as the background and the solid color brush as the foreground.

The following is a reference clip:
Protected override void onpaintbackground (painteventargs E)
{
Base. onpaintbackground (E );
Graphics bggraphics = E. graphics;
Bggraphics. setclip (textregion, combinemode. Exclude );
Bggraphics. fillrectangle (backgroundbrush, E. cliprectangle );
Bggraphics. Dispose ();
}

The onpaintbackground method defined above calls the base class method immediately, which ensures that all the code drawn at the underlying layer can be executed. Next, obtain the graphics object from painteventargs, and define the cut area of the graphics object as the textregion object. By specifying the combinemode. Exclude parameter, it is clear that the textregion area is not drawn no matter where the graphics object is drawn or how it is drawn.

The following is a reference clip:
Protected override void onpaint (painteventargs E)
{
Base. onpaint (E );
Graphics fggraphics = E. graphics;
Fggraphics. fillregion (foregroundbrush, textregion );
Fggraphics. Dispose ();
}

Finally, the onpaint event is responsible for accurately drawing strings. You can easily call the fillregion method of graphics. Use the specified foreground brushes foregroundbrush and textregion, and only the area is drawn. As a result, the Windows form program does "think" about how to draw before running it.

The textclipping example program uses the Windows Forms string defined by region. This allows the program to avoid an area during painting.

You can use the appropriate combination of area and smart re-painting to write the drawing code that runs fast and does not cause flashes, and save memory consumption compared to the use of dual-buffer painting separately.

  Conclusion

If your program is determined to plot, several techniques can be used to enhance the rendering performance. Make sure that setting control properties and appropriate paint event processing are the beginning of robust programming. After balancing the advantages and disadvantages, you can use the dual Buffer technology to produce a very "visual protection" result. Finally, it is helpful to think about which customer regions or region needs to be drawn before actually drawing.

It is hoped that this article will help readers better understand the. NET Framework rendering technology and its application.

 

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.