当前位置:网站首页>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
边栏推荐
- Implementation principle of redis string and sorted set
- How to display √ 2 on the command line terminal ̅? This is actually a blog's Unicode test article
- C language - Introduction - Foundation - syntax - [variable, constant light, scope] (V)
- Flutter 小技巧之 ListView 和 PageView 的各种花式嵌套
- Global and Chinese market of planar waveguide optical splitter 2022-2028: Research Report on technology, participants, trends, market size and share
- Multilingual Wikipedia website source code development part II
- Analysis report on the production and marketing demand and investment forecast of tellurium dioxide in the world and China Ⓣ 2022 ~ 2027
- Report on research and investment prospect prediction of China's electronic grade sulfuric acid industry (2022 Edition)
- Clion console output Chinese garbled code
- 2022-2028 global special starch industry research and trend analysis report
猜你喜欢
2022-2028 global visual quality analyzer industry research and trend analysis report
2022-2028 research and trend analysis report on the global edible essence industry
LeetCode 74. Search 2D matrix
Implementation principle of redis string and sorted set
Some points needing attention in PMP learning
Function comparison between cs5261 and ag9310 demoboard test board | cost advantage of cs5261 replacing ange ag9310
How does idea withdraw code from remote push
2022-2028 global industry research and trend analysis report on anterior segment and fundus OTC detectors
How to batch change file extensions in win10
2022-2028 global special starch industry research and trend analysis report
随机推荐
What is uid? What is auth? What is a verifier?
C语言-入门-基础-语法-[运算符,类型转换](六)
《网络是怎么样连接的》读书笔记 - WEB服务端请求和响应(四)
After unplugging the network cable, does the original TCP connection still exist?
Trees and graphs (traversal)
Global and Chinese markets of thrombography hemostasis analyzer (TEG) 2022-2028: Research Report on technology, participants, trends, market size and share
Write a jison parser from scratch (4/10): detailed explanation of the syntax format of the jison parser generator
C language - Introduction - Foundation - syntax - [operators, type conversion] (6)
Implementing expired localstorage cache with lazy deletion and scheduled deletion
Les différents modèles imbriqués de listview et Pageview avec les conseils de flutter
Write a jison parser (7/10) from scratch: the iterative development process of the parser generator 'parser generator'
Reading notes of how the network is connected - understanding the basic concepts of the network (I)
Trim leading or trailing characters from strings- Trim leading or trailing characters from a string?
Global and Chinese market of air fryer 2022-2028: Research Report on technology, participants, trends, market size and share
C語言-入門-基礎-語法-[運算符,類型轉換](六)
Global and Chinese PCB function test scale analysis and development prospect planning report Ⓑ 2022 ~ 2027
2022-2028 global small batch batch batch furnace industry research and trend analysis report
Ultimate bug finding method - two points
Sword finger offer 30 contains the stack of Min function
Launpad | 基礎知識