Summary of C# GDI+ winform drawing knowledge

1. Graphics

GDI+ is the successor of GDI (Windows Graphics Device Interface). It is an application programming interface provided by .NET Framework for operating graphics. It is mainly used to draw various graphics images on the form, and can be used to draw various data images, mathematics simulation etc.

The Graphics class is the core of GDI+, which provides methods for drawing objects to explicit devices. The Graphics class encapsulates methods for drawing straight lines, curves, circles, images, and text, and is the base class for all GDI+ operations. Before drawing, a Graphics object must be created on the specified form to call the method of the Graphics class to draw.

1. Create Graphics class object
1. Paint event
Create it in the Paint event of the form or control, and use it as a part of PaintEventArgs. This method is typically used when creating drawing code for a control.

For example, to create a Graphics object in the Paint event:

public partial class Form1 : Form
{
    
    
    protected override void OnPaint(PaintEventArgs e)
    {
    
    
        base.OnPaint(e);
 
        Graphics g = e.Graphics; // e.ClipRectangle;//剪切区域,即被遮挡的部分
        g.DrawLine(Pens.Wheat, 0, 0, 2, 2);
    }
}

2. CreateGraphics method

Call the CreateGraphics method of a form or control to obtain a reference to the Graphics object that represents the drawing screen of the control or form. This method should be used if drawing on an existing form or control

For example, in the Load event of the form, the Graphics object is created through the CreateGraphics method

private void Form1_Load(object sender, EventArgs e)    //窗体的Load事件
{
    
    
    Graphics g;    //声明一个Graphics对象
    g = this.CreateGraphics();
}

3, Graphics.FromImage method

To create a Graphics object from any object inherited from Image, just call the Graphics.FromImage method. This method is very useful when you need to change an existing image, for example:

private void Form1_Load(object sender, EventArgs e)
{
    
    
    Bitmap mbit = new Bitmap(@"C:\test.bmp");
    Graphics g = Graphics.FromImage(mbit);
}

2. Properties of the Graphics class

Clip Gets or sets the Region, which bounds the drawing area of ​​this Graphics.
ClipBounds Gets a RectangleF structure that bounds the clipping region of this Graphics.
VisibleClipBounds Gets the bounds of this Graphics' visible clipping region.
CompositingQuality Gets or sets the rendering quality of composite images drawn to this Graphics.
SmoothingMode Gets or sets the rendering quality of this Graphics.
DpiX Gets the horizontal resolution of this Graphics.
DpiY Gets the vertical resolution of this Graphics.
PageScale Gets or sets the scale between this Graphics' world units and page units.
PageUnit Gets or sets the unit of measure used for page coordinates in this Graphics.

3. Common methods of the Graphics class

Draw a line
DrawLine Draw a line connecting two points specified by a coordinate object
DrawLines Draw a list of line segments connecting a set of Point structures
DrawBezier Draw a Bezier spline defined by four Point structures
DrawBeziers Draw a series of Beziers from an array of Point structures Searle spline
DrawCurve Draw a cardinal spline through a set of specified Point structures Draw a
fillable line
DrawEllipse Draw an ellipse specified by a pair of coordinates, width and height
DrawPath Draw a GraphicsPath object
DrawPie Draw a pie, the pie is defined by a coordinate object , width and height, and the ellipse specified by the two rays
. DrawPolygon draws the polygon defined by a set of Point structures
. DrawRectangle draws the coordinate pair. Rectangles specified by width and height
DrawRectangles Draw a series of rectangles specified by the Rectangle structure
DrawArc Draw an arc, which represents the part of the ellipse specified by a pair of coordinates, width and height FillEllipse Fill the inside of the ellipse defined by the border, which is defined by
a
Specifying FillPath for coordinates, a height, and a width
Fills the interior of a GraphicsPath object
FillPie Fills the interior of a pie
FillPolygon Fills the interior of a polygon FillRectangle Fills the interior of a rectangle
specified by a pair of coordinates, a width, and a height
FillRectangles fills the interior of a matrix of columns specified by the Rectangle structure
FillRegion fills the interior of the Region object draws
strings, pictures, icons
DrawString draws specified text strings at specified positions and with specified Brush and Font objects
DrawIcon draws at specified coordinates by The image represented by the specified Icon object
DrawImage Draws the specified Image object at the specified position and at its original size
Others
MeasureString(String, Font) Measures the specified string drawn with the specified Font.
FromImage Creates a Graphics object for the row from the specified Image object
Save Saves the current state of this Graphics object, and the GraphicsState object identifies the saved state
Clear Clears the entire drawing surface and fills it with the specified background color
Dispose Releases all resources used by this Graphics object

2. Coordinate system

GDI+ defines three coordinate systems and provides three coordinate conversion methods Graphics.TransformPoints().

Global coordinate system.
Page coordinate system: the upper left corner is the origin, the horizontal x-axis is positive to the right, and the vertical y-axis is downward to the positive direction. The unit is pixel. This is the default coordinate system.
Device coordinate system: You can specify the page coordinate system of a specific unit of measurement. If the unit is pixel, it is the same as the page (Page) coordinate system.
1. Point structure: Point and PointF
The point structure has two members: X, Y, which represent the coordinates of the x-axis and y-axis of the point. Its common constructors are as follows:

Point p1=new Point(int X,int Y);//X,Y为整数
PointF p2=new PointF(float X,floa Y);//X,Y为浮点数

2. Size structure Size and SizeF
Size and SizeF are used to indicate the size, and there are two members: Width and Height. Commonly used constructors are as follows:

public Size(int width,int height);
public SizeF(float width,float height);

3. Rectangle structure Rectangle and RectangleF
structure Rectangle and RectangleF are used to represent a rectangle, and the common attributes are as follows:

Top, Left, Bottom, Right: Rectangle structure coordinates
Width, Height: Get or set the width and height of this Rectangle structure.
Size: Gets or sets the size of this Rectangle.
X, Y: Get or set the x, Y coordinates of the upper left corner of this Rectangle structure.
Its common constructor is:


//The parameter is the point structure location of the coordinates of the upper left corner of the rectangle and the Size structure size Rectangle(Point location,Size size) representing the width and height of the rectangle;//The parameters can also be PointF and SizeF
//The parameters are x and y of the upper left corner of the rectangle Coordinates, width, height
Rectangle(int X, int Y, int width, int height);//X and Y can also be float
4. Path class GraphicsPath
GraphicsPath class represents a series of interconnected straight lines and curves. This class cannot be inherited.

Graphics g = e.Graphics;
g.FillRectangle(Brushes.White, this.ClientRectangle);
 
GraphicsPath gp = new GraphicsPath();
 
gp.AddLine(10, 10, 10, 50);
gp.AddBezier(10, 50, 10, 55, 25, 70, 30, 70);
gp.AddLine(30, 70, 60, 70);
//闭合图形
gp.CloseFigure();
 
//GraphicsPath类本身没有提供显示创建路径的功能,所以需要把路径对象传给Graphics类的一个方法来显示
g.DrawPath(Pens.Black, gp);
g.FillPath(Brushes.Orange, gp);//给路径填充橘黄色,
gp.Dispose();
g.Dispose();

5. Region class Region class
The Region class represents the interior of a graphic shape composed of a rectangle or a path

1. Create an area from the GraphicsPath path object,

GraphicsPath gp = new GraphicsPath();
 
gp.AddLine(10, 10, 10, 50);
gp.AddBezier(10, 50, 10, 55, 25, 70, 30, 70);
gp.AddLine(30, 70, 60, 70);
//闭合图形
gp.CloseFigure();
 
Region reg = new Region(gp);   //从GraphicsPath对象创建Region对象
//填充区域
g.FillRegion(Brushes.Green, reg);

2. Create from various graphics:

Region reg = new Region(new Rectangle(10, 10, 80, 20));

3. Create another region from one region

Region r1 = new Region(new Rectangle(10, 10, 80, 20));
RegionData r1Data = r1.GetRegionData();//区域数据
Region r2 = new Region(r1Data);  //构造函数不接受区域对象本身,可以接受区域数据数组。

4. Union and intersection of regions

Example:

Graphics g = e.Graphics;
Rectangle rect1 = new Rectangle(50, 10, 50, 130);
Rectangle rect2 = new Rectangle(10, 50, 130, 50);
//设置Region为第一个矩形
Region reg = new Region(rect1);
//用Rect2提取Region中的交集
reg.Intersect(rect2);
 
g.FillRegion(Brushes.Orange, reg);
g.DrawRectangle(Pens.Black, rect1);
g.DrawRectangle(Pens.Black, rect2);

3. Color
1. Color structure
The Color structure represents the color, and the structure contains an unsigned 32-digit number representing the color. Any color can be represented by ARGB colors (alpha, red, green, blue). The Color struct exposes 140 named colors via declarative properties. . Common methods are as follows:

public static Color FromArgb(int alpha,int rr,int gg,int bb);

Creates a Color structure from four component (transparency, red, green, and blue) values. The value of each component is limited to 8 bits (less than 256). The alpha value indicates transparency, =0 is completely transparent, =255 is completely opaque

public static Color FromArgb(int rr,int gg,int bb);

Creates a Color structure from the specified 8-bit color values ​​(red, green, and blue). The transparency value defaults to 255 (fully opaque). The value of each component is limited to 8 bits (less than 256). Red is (255,0,0), green is (0,255,0), and blue is (0,0,255).
public static Color FromArgb(int alpha,Color color);
Creates a new Color structure from the specified Color structure, using the newly specified alpha value alpha. Alpha values ​​are limited to 8 bits.
create instance

//The parameters for creating a Color instance are r, g, b; //The parameters are three primary colors of red, green, and blue, and the transparency is the default, that is, completely opaque.
Color cl = Color.FromArgb(200, 200, 200);

// Call the static FromName method
Color cl = Color.FromName("PowderBlue"); // The string parameter must contain the name of a KnownColor enumeration value.
Use color:

Color red=Color.Red;
red.GetBrightness();
red.GetHue();
red.GetSaturation();

2. ColorTranslator class
FromHtml(String) translates HTML color representation into GDI+ Color structure.

Color myColor = ColorTranslator.FromHtml("Blue");
Color myColor = ColorTranslator.FromHtml("H00000");
ToHtml(Color)    将指定的 Color 结构翻译成 HTML 字符串颜色表示形式。
string htmlColor = ColorTranslator.ToHtml( Color.Red);
string htmlColor = ColorTranslator.ToHtml( Color.FromArgb(255,255,255));

Fourth, the brush Pen class
The brush defines the object used to draw straight lines and curves.

Define the brush:

Pen pen1 = new Pen(Color, Single); //参数为颜色Color,单精度浮点数Sigle;宽度默认为1;
Pen pen2 = Pen(Brush, Single);  // 使用指定的 Pen 和 Brush 初始化 Width 

A new instance of the class.
Use brushes:

//画实线
Pen pen = new Pen(Color.Red, 3);
//确定线的首位位置
Point point1 = new Point(10, 50);
Point point2 = new Point(250, 50);
Graphics g = this.CreateGraphics();
g.DrawLine(pen, point1, point2);

5. Brush Brush
: Define objects used to fill the interior of graphic shapes (such as rectangles, ellipses, pies, polygons, and closed paths). Just an abstract base class.

Rectangle rect1 = new Rectangle(20, 80, 250, 100);
 
// (实心实心刷)
SolidBrush sbrush = new SolidBrush(Color.DarkOrchid);
 
//(纹理刷)
TextureBrush textureBrush = new TextureBrush(new Bitmap(@"e:/123.jpg"));
 
//(梯度、线性渐进刷)
LinearGradientBrush lbrush = new LinearGradientBrush(rect1, Color.DarkOrange, Color.Aquamarine, 45);
 
//路径渐进画刷
PathGradientBrush pathbrush = new PathGradientBrush(graphicsPath);
 
//(阴影刷)
HatchBrush hbrush = new HatchBrush(HatchStyle.DiagonalCross, Color.DarkOrange, Color.Aquamarine);
 
e.Graphics.FillRectangle(sbrush, rect1);         // (实心刷)
e.Graphics.FillRectangle(textureBrush, rect1);       //(纹理刷)
e.Graphics.FillRectangle(lbrush, rect1);            //(梯度刷)
e.Graphics.FillRectangle(hbrush, rect1);             //(阴影刷)

6. Font Font The
Font class has two constructors:

The first is new Font(font name, font size), for example, label1.Font=new Font("Heiti",9).

The second is new Font (font name, font size, font style), where the third parameter is an enumeration type.

Define the font:

//例如修改标签控件字体为斜体:
label1.Font=new Font("黑体",9,label1.Font.Style|FontStyle.Italic);
 
//修改标签控件字体不为斜体:
label1.Font=new Font("黑体",9,label1.Font.Style&~FontStyle.Italic);
字体用法



// Create font and brush.
Font drawFont = new Font("Arial", 16);
SolidBrush drawBrush = new SolidBrush(Color.Black);
 
// Draw string to screen.
e.Graphics.DrawString("Sample Text", drawFont, drawBrush,  new PointF(150.0F, 150.0F));

おすすめ

転載: blog.csdn.net/m0_65636467/article/details/129152793