当前位置:网站首页>C # use gdi+ to add text with center rotation (arbitrary angle)
C # use gdi+ to add text with center rotation (arbitrary angle)
2022-07-04 09:34:00 【Dandelion_ drq】
This article is GDI+ Summarize the third part of the series , If the GDI+ The basic use of unfamiliar friends can read the first article 《C# Use GDI+ drawing 》.
demand
The requirement is to add text rotated at any angle to the picture , The rotation center of the text should be in the center of the text area , It's like CSS Of rotate The same effect as the function . as follows :
analysis & Ideas
Graphics Class has a RotateTransform Method , You can pass in the value of any angle to rotate the palette . But the rotation center of this method is the upper left corner of the drawing board , So directly using this method alone cannot meet our needs . Besides ,Graphics Class has another TranslateTransform Method can change the origin of coordinates , And this method is along the rectangle x,y Axis translational , That is, even if the picture rotates a certain angle , Call again TranslateTransform Method , It still follows x,y Axis translation . Therefore, the image center rotation can be realized through the following three steps .
- Put the drawing board (Graphics object ) The origin is translated to the center of the rectangle (x, y)
- stay (x, y) Position rotate the sketchpad around the origin N degree
- The drawing board is returned (-x, -y) Distance of
If you still can't understand it, you should understand it by looking at the figure below 
Understand the principle , It's not easy to infer , If the center to be rotated is not the center of the picture but the center of the text , That step is the same , Just put (x, y) Just change to the coordinates of the text Center .
In addition to the methods mentioned above , In fact, there is another way to realize the center rotation , That's using Matrix class .Matrix Class RotateAt Method can specify the center position of matrix rotation .
//
// Abstract :
// Along the point Parameter and by pre calculating the rotation , To rotate this clockwise System.Drawing.Drawing2D.Matrix.
//
// Parameters :
// angle:
// Rotation Angle ( Range )( Company : degree ).
//
// point:
// One System.Drawing.PointF, Represents the center of rotation .
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void RotateAt(float angle, PointF point);
Graphics Class Transform Property returns Matrix object , This property can get、set. So we first get the matrix of the original Sketchpad , And then use RotateAt Method to rotate the matrix , Then assign the rotated matrix to the drawing board .
Concrete realization
- Add any angle text method
/// <summary>
/// Add arbitrary angle text to the picture ( Text rotation is the center rotation , The angle is positive clockwise )
/// </summary>
/// <param name="imgPath"> Picture path </param>
/// <param name="locationLeftTop"> The upper left corner of the text is positioned (x1,y1)</param>
/// <param name="fontSize"> font size , In pixels </param>
/// <param name="text"> Written content </param>
/// <param name="angle"> Text rotation angle </param>
/// <param name="fontName"> Font name </param>
/// <returns> After adding text Bitmap object </returns>
public Bitmap AddText(string imgPath, string locationLeftTop, int fontSize, string text, int angle = 0, string fontName = " Chinese Xingkai ")
{
Image img = Image.FromFile(imgPath);
int width = img.Width;
int height = img.Height;
Bitmap bmp = new Bitmap(width, height);
Graphics graphics = Graphics.FromImage(bmp);
// Draw the base map
graphics.DrawImage(img, 0, 0, width, height);
Font font = new Font(fontName, fontSize, GraphicsUnit.Pixel);
SizeF sf = graphics.MeasureString(text, font); // Calculate the rectangular area occupied by the text
// Top left positioning
string[] location = locationLeftTop.Split(',');
float x1 = float.Parse(location[0]);
float y1 = float.Parse(location[1]);
// Position the angle of text rotation
if (angle != 0)
{
#region Law 1 :TranslateTransform translation + RotateTransform rotate
/* * Be careful : * Graphics.RotateTransform The rotation of is in Graphics The upper left corner of the object is the origin , Rotate the whole drawing board . * meanwhile x,y The coordinate axis will also rotate . That is, after rotation x,y The axis is still parallel to the edge of the rectangle * and Graphics.TranslateTransform Method , It's along x,y Axis translational * Therefore, the center rotation can be realized in three steps * 1. Put the drawing board (Graphics object ) Translate to the center of rotation * 2. Rotating Sketchpad * 3. Pan the drawing board back the same distance ( At this time x,y The axis is still parallel to the rotated rectangle ) */
Put the origin of the drawing board ( The default is the upper left corner ) Positioning moves to the center of the text
//graphics.TranslateTransform(x1 + sf.Width / 2, y1 + sf.Height / 2);
Rotating Sketchpad
//graphics.RotateTransform(angle);
Go back to the drawing board x,y The distance the axis has moved
//graphics.TranslateTransform(-(x1 + sf.Width / 2), -(y1 + sf.Height / 2));
#endregion
#region Law two : Matrix rotation
Matrix matrix = graphics.Transform;
matrix.RotateAt(angle, new PointF(x1 + sf.Width / 2, y1 + sf.Height / 2));
graphics.Transform = matrix;
#endregion
}
// Write custom angle text
graphics.DrawString(text, font, new SolidBrush(Color.Black), x1, y1);
graphics.Dispose();
img.Dispose();
return bmp;
}
PS: Here is a brief explanation of why the text center is (x1 + sf.Width / 2, y1 + sf.Height / 2), because (x, y) It's the upper left corner , and sf.Width、sf.Height Is the width of the text rectangle 、 high . Pictured :
- Test call
private static void Main(string[] args)
{
try
{
Console.WriteLine("Start drawing ...");
System.Drawing.Bitmap bmp = AddText(@"D:\test\1.png", "176.94,150.48", 66, " Write something good ", 30);
bmp.Save(@"D:\test\output.png");
bmp.Dispose();
Console.WriteLine("Done!");
}
catch (System.Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
System.Console.WriteLine("\nPress any key to continue ...");
System.Console.ReadKey();
}
}
Final effect
When there is no rotation

The center rotates 30 degree

A thought
After talking, let's think about a problem , If I want to rotate the picture around any position as the center, what should I do ? I believe that after reading the above code, everyone should be able to .
Reference article :
C# Based on GDI+(Graphics) Image processing series of arbitrary angle rotation image
Other articles in the series :
C# Use GDI+ Add text to the picture , And make the text adaptive to the rectangular area
边栏推荐
- 2022-2028 global special starch industry research and trend analysis report
- Explain TCP protocol in detail three handshakes and four waves
- 【leetcode】540. A single element in an ordered array
- 2022-2028 global probiotics industry research and trend analysis report
- mmclassification 标注文件生成
- Global and Chinese market of sampler 2022-2028: Research Report on technology, participants, trends, market size and share
- 《网络是怎么样连接的》读书笔记 - FTTH
- `Example of mask ` tool use
- 如何编写单元测试用例
- You can see the employment prospects of PMP project management
猜你喜欢

2022-2028 global protein confectionery industry research and trend analysis report

Mac platform forgets the root password of MySQL

Leetcode (Sword finger offer) - 35 Replication of complex linked list

Nurse level JDEC addition, deletion, modification and inspection exercise

Four common methods of copying object attributes (summarize the highest efficiency)

LeetCode 74. Search 2D matrix

PHP personal album management system source code, realizes album classification and album grouping, as well as album image management. The database adopts Mysql to realize the login and registration f

2022-2028 global tensile strain sensor industry research and trend analysis report

After unplugging the network cable, does the original TCP connection still exist?
![C language - Introduction - Foundation - syntax - [variable, constant light, scope] (V)](/img/dc/5c8077c10cdc7ad6e6f92dedfbe797.png)
C language - Introduction - Foundation - syntax - [variable, constant light, scope] (V)
随机推荐
China battery grade manganese sulfate Market Forecast and strategic consulting report (2022 Edition)
Lauchpad x | MODE
After unplugging the network cable, does the original TCP connection still exist?
回复评论的sql
2022-2028 global tensile strain sensor industry research and trend analysis report
Report on investment analysis and prospect trend prediction of China's MOCVD industry Ⓤ 2022 ~ 2028
Write a jison parser from scratch (2/10): learn the correct posture of the parser generator parser generator
Launpad | 基础知识
《网络是怎么样连接的》读书笔记 - 认识网络基础概念(一)
Review of last week's hot spots (6.27-7.3)
How to write unit test cases
Explain TCP protocol in detail three handshakes and four waves
"How to connect the network" reading notes - Web server request and response (4)
PHP book borrowing management system, with complete functions, supports user foreground management and background management, and supports the latest version of PHP 7 x. Database mysql
《网络是怎么样连接的》读书笔记 - 集线器、路由器和路由器(三)
Trees and graphs (traversal)
2022-2028 global special starch industry research and trend analysis report
Global and Chinese markets for laser assisted liposuction (LAL) devices 2022-2028: Research Report on technology, participants, trends, market size and share
Svg image quoted from CodeChina
165 webmaster online toolbox website source code / hare online tool system v2.2.7 Chinese version