当前位置:网站首页>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
边栏推荐
- How does idea withdraw code from remote push
- 165 webmaster online toolbox website source code / hare online tool system v2.2.7 Chinese version
- How to write unit test cases
- Write a jison parser (7/10) from scratch: the iterative development process of the parser generator 'parser generator'
- UML sequence diagram [easy to understand]
- mmclassification 标注文件生成
- "How to connect the Internet" reading notes - FTTH
- Global and Chinese markets of thrombography hemostasis analyzer (TEG) 2022-2028: Research Report on technology, participants, trends, market size and share
- Dynamic analysis and development prospect prediction report of high purity manganese dioxide in the world and China Ⓡ 2022 ~ 2027
- Rules for using init in golang
猜你喜欢

HMS core helps baby bus show high-quality children's digital content to global developers

Function comparison between cs5261 and ag9310 demoboard test board | cost advantage of cs5261 replacing ange ag9310

2022-2028 global optical transparency industry research and trend analysis report
](/img/3f/4d8f4c77d9fde5dd3f53ef890ecfa8.png)
C語言-入門-基礎-語法-[運算符,類型轉換](六)

Opencv environment construction (I)
](/img/3f/4d8f4c77d9fde5dd3f53ef890ecfa8.png)
C语言-入门-基础-语法-[运算符,类型转换](六)

2022-2028 global intelligent interactive tablet industry research and trend analysis report

2022-2028 global industrial gasket plate heat exchanger industry research and trend analysis report

LeetCode 74. Search 2D matrix

Four common methods of copying object attributes (summarize the highest efficiency)
随机推荐
Summary of the most comprehensive CTF web question ideas (updating)
"How to connect the Internet" reading notes - FTTH
You can see the employment prospects of PMP project management
2022-2028 global gasket metal plate heat exchanger industry research and trend analysis report
Analysis report on the production and marketing demand and investment forecast of tellurium dioxide in the world and China Ⓣ 2022 ~ 2027
Basic data types in golang
2022-2028 global intelligent interactive tablet industry research and trend analysis report
Implementation principle of redis string and sorted set
2022-2028 global seeder industry research and trend analysis report
lolcat
Nurse level JDEC addition, deletion, modification and inspection exercise
Analysis report on the development status and investment planning of China's modular power supply industry Ⓠ 2022 ~ 2028
At the age of 30, I changed to Hongmeng with a high salary because I did these three things
什么是uid?什么是Auth?什么是验证器?
Dynamic analysis and development prospect prediction report of high purity manganese dioxide in the world and China Ⓡ 2022 ~ 2027
Jianzhi offer 09 realizes queue with two stacks
2022-2028 global special starch industry research and trend analysis report
2022-2028 global strain gauge pressure sensor industry research and trend analysis report
Daughter love: frequency spectrum analysis of a piece of music
In depth investigation and Strategic Research Report on China's motion controller Market (2022 Edition)