. NET frame using double buffering technology drawing

Source: Internet
Author: User
Tags implement message queue requires variable
The. NET Framework

This article mainly introduces the basic drawing technology of the. Net Framework. The advantages, disadvantages and other related considerations of drawing technology are discussed through a brief introduction and a sample program.

   Brief Introduction

Fortunately, when you write a typical Windows Forms program, the drawing, effects, and so on of forms and controls do not need to be specifically considered. What is this for? Because by using the. Net Framework, developers can drag a series of controls onto a 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 themselves, and the form or control is resized and scaled. What is often used here is a control effect that requires a little attention. Games, custom chart controls, and the writing of screen savers require programmers to write additional code to respond to Paint events.

This article is intended for those Windows Forms developers and helps them to use simple drawing techniques in the application preparation process. First, we'll discuss some basic drawing concepts. Who is in charge of drawing operations? How does a Windows forms program know when to draw? Where are the drawing codes placed? After that, you will also introduce the dual buffer technology for image rendering, and you will see how it works, and how to use a method to achieve alternating between cached and actually displayed images. Finally, we'll explore the "Smart Invalid Zone," which is actually simply redrawing or clearing the invalid part of the application form, speeding up the program's display and response speed. Hopefully these concepts and techniques will guide readers through this article and help develop Windows Forms programs faster and more efficiently.

Windows Forms uses the GDI + image engine, and all of 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 a fast, efficient technique and method for improving program performance. So, before you read through this article, recommend to the reader. NET Framework has a basic understanding, including Windows Forms event handling, 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, and when a form is "dirty"-that is, the form changes size, or is partially obscured by other program forms, or resumes from a minimized state-the program receives information that needs to be drawn. Windows makes this "dirty" state known as an "invalid (invalidated)" state, which we understand is that it needs to be redrawn, and it gets the drawn information from the Windows message Queue when the Windows Forms program needs to redraw the form. This information passes by. NET Framework is encapsulated and then passed to the Paintbackground and Paint events of the form, in which the appropriate writing of the code specifically for drawing is possible.

A simple drawing example is as follows:

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 code above is divided into two basic steps to create the sample program. First, the InitializeComponent method contains the settings for some properties and the process of attaching a form Paint event. Note that the style of the control in the method is also set, and setting the control's style is also an effective way to customize Windows Forms and control behavior, such as: the "Resizeredraw" property of the control indicates that it needs to be fully redrawn when the form's size changes occur. This means that the client area of the entire form needs to be redrawn when redrawing. The customer area of the form refers to all the form regions except for the title bar and border. You can do an interesting experiment by canceling the properties of the control and then running the program, and we can see why the property is often set because the invalid area after the form is resized is not redrawn 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 redrawing, and the program form uses the Paint event to respond to system messages that need to be redrawn, and the call to Basicx_paint method requires an object Sender and a PaintEventArgs type of variable, an instance of the PaintEventArgs class or a variable E that encapsulates two important data, the first is the Graphics object of the form, which means that the surface that the form can draw is also called a canvas for drawing such as a line , text, images, and so on, the second data is ClipRectangle, which represents an invalid rectangular range on a form, or an area that the form needs to redraw. Remember that when the form's Resizereddraw is set, the size of the cliprectangle is actually equal to the size of the entire customer area of the form, or the part of the clipping area that is obscured by other program forms. The use of parts of the shear area is explained in more detail in the Smart Redraw section.


Basicx the running interface of the sample program

  Double buffer Plotting technology

Dual buffer technology can make the program's drawing faster and smoother, effectively reduce the image flicker when drawing. The basic principle of this technique is to draw the image to a canvas in memory first, and once all the drawing operations are complete, then push the canvas in memory to the form or the surface of the control to display it. The procedure after this operation can make the user feel it faster and more beautiful.

The sample program provided below illustrates the concept and implementation of a dual buffer, which is fully functional and can be used in practical applications. It is also mentioned later in this chapter that the technique should work with some of the control's property settings to achieve better results.

To appreciate the benefits of dual-buffer mapping technology, run the Spiderweb sample program. After the program starts and runs to resize the window, you will find that the drawing algorithm is inefficient and there is a lot of flicker during resizing.


Spiderweb sample programs that do not have dual buffer technology


Look at the source code of the program you will find in the program Paint event activation is by calling the Linedrawroutine method to achieve the drawing of the line. The Linedrawroutine method has two parameters, the first is the place where the graphics object is used to draw the line, and the second is the drawing tool pen object to draw the line. The code is fairly simple, a looping statement, a Linefreq constant, and so on, the program dashes from the bottom left of the form surface to the top right. Note that the program uses floating-point numbers to calculate where to draw on a form, and the advantage is that the position data is more accurate when the form's size changes.

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 very simple code to respond to the paint event Spiderweb_paint, as mentioned earlier, the Graphics object is the drawing surface of a form that is extracted from the paint event parameter PaintEventArgs object. This graphics object, along with the newly created Pen object, is passed to the Linedrawroutine method to draw a cobweb-like line, and the entire drawing operation is completed when the graphics object and the Pen object are used to free the resources it occupies.

private void Spiderweb_paint (object sender, PaintEventArgs e) {
Graphics g = e.graphics;
Pen redpen = new Pen (color.red);
Call our isolated drawing routing
Linedrawroutine (g, redpen);
Redpen.dispose ();
G.dispose ();
}
So what kind of changes to make the above Spiderweb program to achieve a simple double buffer technology? The principle is quite simple, that is, the painting should be drawn to the surface of the form to the first painting into the memory of the bitmap, linedrawroutine to this hidden in memory in the canvas to perform the same spider Web Drawing operations, Wait until the drawing is finished and then call the Graphics.DrawImage method to display the contents of the hidden canvas onto the surface of the form, and finally, with some minor changes, a high-performance drawing form program is completed.

Compare the differences between the following double buffer drawing events and the simple drawing events described earlier:

private void Spiderweb_dblbuff_paint (object sender, PaintEventArgs e) {
Graphics g = e.graphics;
Pen Bluepen = new Pen (color.blue);
Create our offscreen bitmap
Bitmap Localbitmap = new Bitmap (clientrectangle.width,clientrectangle.height);
Graphics bitmapgraphics = Graphics.fromimage (Localbitmap);
Call our isolated drawing routing
Linedrawroutine (Bitmapgraphics, Bluepen);
Push our bitmap forward to the screen
G.drawimage (localbitmap, 0, 0);
Bitmapgraphics.dispose ();

Bluepen.dispose ();
Localbitmap.dispose ();
G.dispose ();
}
The example code above creates a memory bitmap object that is equal to the size of the customer area (that is, the drawing surface) of the form. A reference to an in-memory bitmap is passed to the graphics object by calling Graphics.fromimage, which means that all subsequent operations on the Graphics object actually operate on the in-memory bitmap, which operates in C + + is equivalent to copying a bitmap object's pointer to a graphics object, with two objects using the same memory address. Now the Graphics object represents a canvas behind the screen, which plays a crucial role in the dual-buffer technology. All line-drawing operations have been directed to an in-memory bitmap object, and the next step is to copy the bitmap to the form by calling the DrawImage method, which immediately appears on the drawing surface of the form and does not blink at all.

This series of operations is not particularly effective since we mentioned earlier that the style of the control is also a way to define the behavior of Windows Forms programs, for better implementation of dual buffers you must set the control's Opaque property, which indicates that the form is not responsible for drawing itself in the background, In other words, if this property is set, then the associated code must be added for the purge and redraw operations. A dual buffer version of the Spiderweb program through the above settings in each need to redraw the performance, the surface of the form with its own background color to clear, so that the more reduced flicker.

Public Spiderweb_dblbuff () {
SetStyle (Controlstyles.resizeredraw | Controlstyles.opaque, True);
}

private void Spiderweb_dblbuff_paint (object sender, PaintEventArgs e) {
//create our offscreen bitmap< br> Bitmap localbitmap = new Bitmap (clientrectangle.width, clientrectangle.height);
Graphics bitmapgraphics = Graphics.fromimage (Localbitmap);
Bitmapgraphics.clear (BackColor);
//call Our isolated drawing routing
Linedrawroutine (bitmapgraphics, Bluepen);
}
What's the result? The rendering of the image is much smoother. The line from memory to the front of the web to the foreground to show that there is no flicker, but we still a little pause, first in the memory of the bitmap trimmed and then displayed, you can add a line of code to make the line look more flat.  

Bitmapgraphics.smoothingmode = Smoothingmode.antialias;
After assigning an in-memory bitmap object to graphics, by placing this line of code, each line we draw on the canvas uses anti-aliasing to make the uneven lines appear more flat.


Spiderweb_dblbuff sample program with dual buffer technology and using antialiasing (anti-aliasing) Properties


After completing the simple double buffer application, there are two issues that need to be clarified to the reader. NET, such as Button, PictureBox, label, and PropertyGrid, have been used to make good use of the technology! These controls automatically enable dual buffer technology by default, and users can implement dual buffer technology by setting the "DoubleBuffer" property. So it would be more efficient for users to use PictureBox to draw cobwebs, and it would make the program easier.

The dual buffer technology we are discussing here is neither completely optimized but has no significant negative impact. Dual-buffer technology is an important way to reduce the flicker of Windows Form drawing, but it does consume a lot of memory because it will use double the memory space: the image displayed by the application and the image in the rear of the screen. Bitmap objects are created dynamically each time the paint event is activated, which can be quite memory-intensive. A control that has a dual buffer technique can perform better with the DoubleBuffer property.

Using GDI + 's DIB (device-independent bitmap) object to implement a memory buffer other than this, a control with a dual buffer mechanism can make good use of the bitmap object. The DIB is the underlying Win32 object for efficient screen drawing. Similarly, it is noteworthy that the first version of GDI + is related only to hardware acceleration and that some simple features can be used directly, and because of this limitation, screen-drawing methods such as anti-aliasing and translucency are slow to execute. Although the dual buffer mechanism consumes some memory, its use undoubtedly enhances the execution performance of the program.

  Smart redraw, need to weigh before drawing

"Smart" (smart redraw) is a hint that programmers should understand that only areas that are not valid in the program should be redrawn. Redrawing the invalid area corresponding to the regions object can improve the rendering performance, and you can use the regions object to exclude or plot only parts of the control and form for better performance. Let's start by looking at the Basicclip sample program, which uses the ClipRectangle object that is saved in the PaintEventArgs object, which we've mentioned before, whenever the size of the program changes, the Paint event is activated. The Basicclip sample program fills the clipped rectangular area with red and blue colors, adjusts the size of the form at different speeds after a few times, you'll find that the rectangular area you draw is actually an invalid area of the form (including areas that are larger than the size of the original form and less area). The Paint event code for the sample program is as follows:

private void Basicclip_paint (object sender, PaintEventArgs e) {
Graphics g = e.graphics;
Swap colors
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 the sample program is to demonstrate how to draw only for parts of the region.


The color rectangular area in the Basicclip sample program is an invalid area that represents the bottom and right sides of the form.


Regions is an object that is used to define a Windows Form or control area, and the regions that you get when you resize the form is the smallest area of the form redrawing. Only special areas of interest are drawn when the program needs to be drawn, so drawing a smaller area makes the program run faster.

For a better demonstration of regions usage, see the Textcliping sample program. This program overloads the OnPaintBackground and OnPaint methods, which are more efficient than listening events to ensure that the code is invoked before other drawing operations, and that the custom control is drawn more efficiently. For clarity, the sample program provides a setup method that defines the global graphics object.

private void Setup () {
GraphicsPath Textpath = new GraphicsPath ();
Textpath.addstring (displaystring, Fontfamily.genericserif,
0, New Point (a), New StringFormat ());
Textregion = new Region (Textpath);
Backgroundbrush = new TextureBrush (New Bitmap ("Coffeebeansmall.jpg"),
Wrapmode.tile);
Foregroundbrush = new SolidBrush (color.red);
}
The above Setup method first defines an empty GraphicsPath object variable Textpath, and the next string "Windows Forms" bounds are added to the path, creating region around the contour. In this way, a region that is drawn to the surface of the form, with a string outline as a region, is created. Finally, the Setup method creates a form with a material brush background and a solid brush for the foreground.

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, as defined above, calls the base class method immediately, which guarantees that all the underlying code can be executed. Next, you get the Graphics object from the PaintEventArgs, and then define the graphics object's clipping region as the Textregion object. By specifying the Combinemode.exclude parameter, it is clear that no matter where it is drawn or how the graphics object is drawn, the Textregion area is not drawn inside.

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 the string. It can be easily implemented by invoking the graphics FillRegion method. Foregroundbrush and textregion with the specified foreground brush and only the area is drawn. As a result, Windows forms programs really "think" about how to draw before running.


Textclipping sample Program, a Windows Forms string defined by region. Enables the program to avoid a region while drawing.


Appropriate combination use area and smart redraw you can write code that runs faster and does not cause flicker, and saves memory when you draw with a single double buffer.

   Conclusions

If your program is determined to draw, use several techniques to enhance the rendering performance. Ensuring that you are trying to set control properties and appropriate paint event handling is the beginning of writing a robust program. After weighing the pros and cons, you can use dual buffer technology to produce very "protective eyesight" results. Finally, it is useful to think before you actually draw which customer areas or region needs to be drawn.

Hopefully, this article will enable readers to better understand the drawing techniques and applications of the. NET Framework.

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.