当前位置:网站首页>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
边栏推荐
- MySQL foundation 02 - installing MySQL in non docker version
- Daughter love: frequency spectrum analysis of a piece of music
- 保姆级JDEC增删改查练习
- 回复评论的sql
- Report on investment analysis and prospect trend prediction of China's MOCVD industry Ⓤ 2022 ~ 2028
- How does idea withdraw code from remote push
- The 14th five year plan and investment risk analysis report of China's hydrogen fluoride industry 2022 ~ 2028
- 2022-2028 global probiotics industry research and trend analysis report
- 法向量点云旋转
- Global and Chinese market of wheel hubs 2022-2028: Research Report on technology, participants, trends, market size and share
猜你喜欢
Markdown syntax
2022-2028 global industry research and trend analysis report on anterior segment and fundus OTC detectors
Dede plug-in (multi-function integration)
C language - Introduction - Foundation - syntax - [identifier, keyword, semicolon, space, comment, input and output] (III)
165 webmaster online toolbox website source code / hare online tool system v2.2.7 Chinese version
保姆级JDEC增删改查练习
2022-2028 global gasket metal plate heat exchanger industry research and trend analysis report
Web端自动化测试失败原因汇总
After unplugging the network cable, does the original TCP connection still exist?
You can see the employment prospects of PMP project management
随机推荐
How does idea withdraw code from remote push
2022-2028 global industry research and trend analysis report on anterior segment and fundus OTC detectors
Global and Chinese markets for laser assisted liposuction (LAL) devices 2022-2028: Research Report on technology, participants, trends, market size and share
【leetcode】540. A single element in an ordered array
Global and Chinese PCB function test scale analysis and development prospect planning report Ⓑ 2022 ~ 2027
2022-2028 global optical transparency industry research and trend analysis report
The old-fashioned synchronized lock optimization will make it clear to you at once!
The 14th five year plan and investment risk analysis report of China's hydrogen fluoride industry 2022 ~ 2028
Report on the development trend and prospect trend of high purity zinc antimonide market in the world and China Ⓕ 2022 ~ 2027
Function comparison between cs5261 and ag9310 demoboard test board | cost advantage of cs5261 replacing ange ag9310
2022-2028 global gasket metal plate heat exchanger industry research and trend analysis report
Global and Chinese market of planar waveguide optical splitter 2022-2028: Research Report on technology, participants, trends, market size and share
QTreeView+自定义Model实现示例
什么是uid?什么是Auth?什么是验证器?
2022-2028 global probiotics industry research and trend analysis report
China electronic grade sulfur trioxide Market Forecast and investment strategy report (2022 Edition)
SSM online examination system source code, database using mysql, online examination system, fully functional, randomly generated question bank, supporting a variety of question types, students, teache
Explanation of for loop in golang
Trim leading or trailing characters from strings- Trim leading or trailing characters from a string?
Are there any principal guaranteed financial products in 2022?