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
Developing with C# .NET: A Practical Guide and ExamplesDeveloping with C# .NET: A Practical Guide and ExamplesMay 12, 2025 am 12:16 AM

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

C# .NET: Understanding the Microsoft .NET FrameworkC# .NET: Understanding the Microsoft .NET FrameworkMay 11, 2025 am 12:17 AM

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

The Longevity of C# .NET: Reasons for its Enduring PopularityThe Longevity of C# .NET: Reasons for its Enduring PopularityMay 10, 2025 am 12:12 AM

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

Mastering C# .NET Design Patterns: From Singleton to Dependency InjectionMastering C# .NET Design Patterns: From Singleton to Dependency InjectionMay 09, 2025 am 12:15 AM

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),