search
C# GDI+ Programming (1)Dec 17, 2016 am 10:20 AM

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
How to add next-level C compilerHow to add next-level C compilerMar 03, 2025 pm 05:44 PM

This article explains how to create newline characters in C using the \n escape sequence within printf and puts functions. It details the functionality and provides code examples demonstrating its use for line breaks in output.

What are the alternatives to NULL in C languageWhat are the alternatives to NULL in C languageMar 03, 2025 pm 05:37 PM

This article explores the challenges of NULL pointer dereferences in C. It argues that the problem isn't NULL itself, but its misuse. The article details best practices for preventing dereferences, including pre-dereference checks, pointer initiali

Which C language compiler is better?Which C language compiler is better?Mar 03, 2025 pm 05:39 PM

This article guides beginners on choosing a C compiler. It argues that GCC, due to its ease of use, wide availability, and extensive resources, is best for beginners. However, it also compares GCC, Clang, MSVC, and TCC, highlighting their differenc

Is NULL still important in modern programming in C language?Is NULL still important in modern programming in C language?Mar 03, 2025 pm 05:35 PM

This article emphasizes the continued importance of NULL in modern C programming. Despite advancements, NULL remains crucial for explicit pointer management, preventing segmentation faults by marking the absence of a valid memory address. Best prac

What are the web versions of C language compilers?What are the web versions of C language compilers?Mar 03, 2025 pm 05:42 PM

This article reviews online C compilers for beginners, focusing on ease of use and debugging capabilities. OnlineGDB and Repl.it are highlighted for their user-friendly interfaces and helpful debugging tools. Other options like Programiz and Compil

Method of copying code by C language compilerMethod of copying code by C language compilerMar 03, 2025 pm 05:43 PM

This article discusses efficient code copying in C IDEs. It emphasizes that copying is an IDE function, not a compiler feature, and details strategies for improved efficiency, including using IDE selection tools, code folding, search/replace, templa

C language online programming website C language compiler official website summaryC language online programming website C language compiler official website summaryMar 03, 2025 pm 05:41 PM

This article compares online C programming platforms, highlighting differences in features like debugging tools, IDE functionality, standard compliance, and memory/execution limits. It argues that the "best" platform depends on user needs,

C language compiler installation tutorial (computer version)C language compiler installation tutorial (computer version)Mar 03, 2025 pm 05:41 PM

This tutorial guides users through installing C compilers on Windows, macOS, and Linux. It details installation for popular compilers (MinGW, Visual Studio, Xcode, GCC), explains environment variable configuration, and offers troubleshooting steps

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software