Home  >  Article  >  Backend Development  >  C# GDI+ Programming (1)

C# GDI+ Programming (1)

高洛峰
高洛峰Original
2016-12-17 10:20:021125browse

Although it is in C++, there are always some similarities.

When the window is refreshed, a Paint event will be generated, so we add a handler function to this event. Then draw the graph in this function. This will ensure that the picture you draw will not be refreshed, and it can always be displayed. The delegate corresponding to the Paint event is: public delegate void PaintEventHandler(object sender, PaintEventArgs e);

Let’s start with the simplest drawing, drawing a line on the window. (Creating a Windows Forms application)

public partial class Form1: Form

{

public Form1()
InitializeComponent();

//Add Pa int event handler
                                                                                                    using   using   use using   using   using using           using using ‐ ‐               through using using        through using ’ ’ through ’ through ’ s Through through through ’ s ’ through ’' ‐ ‐‐ ‐‐‐‐‐‐ Formpaaint (Object SENDER, PAINTEVENTARGS E)

{

Graphics graphics = e.graphics;
// brush, green, 2 pixel wide
pen pen (color.fromargb (0,255,0), 2); 2);
// Draw a line, the two points are 0,0 and 100,100
                graphics.DrawLine(pen, new Point(0,0), new Point(100,100)); There are also pictures, which can all be completed through the Graphics class.

Example 2: A filled rectangle

Graphics graphics = e.Graphics;
//Blue brush
SolidBrush brush = new SolidBrush(Color.FromArgb(0, 0, 255));
//A rectangle

Rectangle rect = new Rectangle(0, 0, 100, 100);

//Fill a rectangle

graphics.FillRectangle(brush, rect);

Example 3: Draw a png picture (PNG is used because it can display transparent pictures , GIF pictures also have this effect)


Private Void Formpaaint (Object SENDER, PAINTEVENTARGS E) {
Graphics Graphics = E.Graphics; d: \ image \ win. png");
                                                                                                                                                                                                                                    .​​​ //Reduce picture drawing, limited to Within a rectangle
            Rectangle rect=new rectangle(50,50,100,100);
                  graphics.DrawImage(img, rect); There are several overloads in the ics class, some of which allow Strings are displayed within a rectangle, and some can use specific display formats. I won’t go into details here.

Only talk about the more commonly used ones.

Look at the example, handle the keyboard input character event and display the entered characters in the window. As follows:

Public partial class Form1: Form
{
public static String strText = "";
public Form1()
InitializeComponent();
This.Paint += formPaint;
this.KeyPress += formKeyPress;

}
private void formPaint(Object sender, PaintEventArgs e)
{
Graphics graphics = e.Graphics;
//Create a brush
SolidBrush brush=new SolidBrush(Color. FromArgb(0,255,0));
                 //Create font
            Font font=new Font("宋体",20f);
                                                                                                                                             private void formKeyPress(object sender, KeyPressEventArgs e)


Also graphics.DrawString(strText, font, brush, new Point(100, 100 ));Display mode, this just specifies the starting position of text display.

See the following example for the display format:

//Display string, within a rectangle
StringFormat strFormat = new StringFormat(StringFormatFlags.DirectionRightToLeft);
graphics.DrawString(strText, font, brush, this.ClientRectangle,strFormat) ;

StringFormatFlags is an enumeration type. Try it one by one to see what format each enumeration member represents.

Next, let’s take a look. What is the relationship between the default event handling method in the Form class and the event handling method you added.

An example: Handling left mouse button events

public partial class Form1: Form
                                                                                                                                              The default background color. MouseDown += formMouseDown; {
                                                                                            use   use   with using using the right button of the mouse                                             e.Button == MOUSEBUTTONS.RIGHT)
{
form1 form1 = (form1) sender;
// change the background color
form1.backcolor = color.fromargb (0, 255, 0); The key to the event (loosen) event treatment method
Private void formmouseup (Object Sender, MOUSEEVENTARGS E) {
if (e.Button == mousebuttons.right) {
form1 form1 = (Form1) ; 1 FORM1.BackColor = prBackColor;

protected virtual void OnMouseDown(MouseEventArgs e); and protected virtual void OnMouseUp(MouseEventArgs e);

In this way, you can handle mouse events without adding an event handling method. You can override the default event handling method of the parent class, to implement the above example.

When checking MSDN, we can find that calling these default event handling methods can trigger corresponding events. For example, if I call OnMouseDown, I can trigger the left mouse button press event, which actually executes the event processing method (delegate) we added. And we still use multicast delegation, because we use "+=" to add the delegation method.

In this case, if you rewrite OnMouseDown, you must call the OnMouseDown method of the base class in it,

Otherwise the MouseDown method we added will not be executed (if any)

Now that I know the above, I will do it Let’s do a practical example. Override the OnPaintBackground method of drawing the background.

public partial class Form1: Form
                                                                                                                                                                                       off                out        off       out           out    out                          out  out  out 
          protected override void OnPaintBackground(PaintEventArgs e)
                                                                                                                           Paint the background yourself
                                                              use   using using use using using                                                                            e.Graphics.FillRectangle(brush,this. ClientRctangle);
// Draw a circle again
Pen Pen = New Pen (color.fromargb (0, 255, 0), 3);
TextureBursh picture brush

You can use pictures to fill a shape, such as rectangle, circle. If the image is not large enough, it will be displayed tiled.

Example: i Prive Void Formpaaint (Object Sender, Painteventargs E)
{
Graphics Graphics = E.Graphics; , 70, 70); 7 TextureBrush Brush = New TextureBrush (Image.fromfile ("D: \ Image \ 345.jpg"), RECT); Number last parameter , rect indicates which part of the image is to be filled, 10,10 indicates the starting position of the image (upper left corner), 70,70 indicates the width and height, be careful not to exceed the original range of the image. If the entire picture is filled, there is no need to specify rect. Just fill in a parameter in the constructor.

LinearGradientBursh linear gradient brush (this class exists in the System.Drawing.Drawing2D namespace)

The LinearGradientBursh class has a constructor overload, which has four parameters, two points, and two colors.

These four parameters specify the color of the starting point and the color of the ending point. And location.

Look at the following example:

Public partial class Form1: Form

{

Public Form1()

InitializeComponent(); InitializeComponent(); this.Pa int += formPaint;

I}

Private Void Formpait (Object SENDER, Painteventargs E)
{
Graphics Graphics = E.Graphics; ENTBRUSH (New Point (0, 0), New Point (50, 0),
color.fromargb (255, 255, 255), color.fromargb (0, 0, 0));
// fill the entire window
Graphics.fillrectangle (linebrush, this.ClientRctangle); The end point is the rendering of 0,50. Gradient color segment from white to black. The part that exceeds 50 starts to fade again.

Just like when using PS, the gradient color is from white to black, and then pull a line. The starting point is 0,0 and the ending point is 0,50.

So what will it look like if I use the gradient brush with this attribute to draw a rectangle in the window? You can know it by looking at the rendering above.

For example, graphics.FillRectangle(lineBrush, 0, 0, 100, 100);

The brush fill of this rectangle is the same as the corresponding rectangular area of ​​the first effect.

You can also see it if you change the values ​​of the start point and end point. How is this filled in?

For example, the starting point is changed to 0,0, and the end point is changed to 50,50. V Private void Formpaaint (Object Sender, Painteventargs E) {

Graphics Graphics = E.Graphics; USH (new point (0, 0), new point (50, 50),

color.fromargb ( 255, 255, 255), Color.FromArgb(0, 0, 0));

            //填充整个窗口

            graphics.FillRectangle(lineBrush, this.ClientRectangle);

            Pen pen = new Pen(Color.FromArgb(0, 255,0); This window does not disable the maximize function, and the window size can be changed for further observation.

Multiple color gradients


The LinearGradientBrush class has an InterpolationColors attribute member that can specify multiple color gradients. This member is a ColorBlend type. Like the previous gradients, they can only be limited to gradients of two colors. After using InterpolationColors, A variety can be used, such as a gradient from red to green, then green to blue.

Look at the example:
V Private Void Formpaaint (Object Sender, Painteventargs E) {

// Create the colorBlend object, specify a variety of color gradient information
colorblend color_blend = new colorblend ();
// specify several colors. L color_blend.colors = new color [ ]{Color.Red,Color.Green,Color.Blue};
                                                     ’ Rectangle(0,0,200,100); or.White);
                                                    brush .InterpolationColors=color_blend; e.Graphics.FillRectangle(brush,rect);
Gradient, then gradient from green to blue.

color_blend.Positions specifies the color range. If the width of the rectangle above is regarded as the overall 1, then the red to green gradient is completed from 0/3f to 2/3f, that is, it is completed within this

range If the gradient from red to green is obtained, then the range of the gradient from green to blue is 2/3f to 3/3f.

If you want to share half and half, it is color_blend.Positions=new float[]{0/2f,1/2f,2/2f};



More C# GDI+ Programming (1) related Please pay attention to the PHP Chinese website for articles!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:C# GDI+ Programming (2)Next article:C# GDI+ Programming (2)