当前位置:网站首页>C # use gdi+ to add text to the picture and make the text adaptive to the rectangular area
C # use gdi+ to add text to the picture and make the text adaptive to the rectangular area
2022-07-04 09:34:00 【Dandelion_ drq】
demand
The requirement is to make a page for editing text . Users write text on the web , The text area is a rectangular box , Users can adjust the text size by dragging the bar below .
Here's the picture :
When submitting data, the upper left corner and lower right corner of the front-end text area are positioned to the background . Because the font size unit of the front end has nothing to do with the back end , So you can't directly transfer the font size , That is, the back end should calculate the appropriate font size according to the rectangular area and text content .
Simply put, you know the rectangular area of the text , And the text , The text content should be adjusted to the appropriate font size according to the size of the rectangular area, which can fill this area appropriately .
analysis & Ideas
Graphics
Class has a MeasureString
Method , It can be used to calculate how many pixels the text written in the current font will occupy .
as follows :
//
// Abstract :
// Specified for measurement System.Drawing.Font Draw the specified string .
//
// Parameters :
// text:
// String to measure .
//
// font:
// System.Drawing.Font, It defines the text format of the string .
//
// Return results :
// This method returns System.Drawing.SizeF structure , The structure represents text Parameter specified 、 Use font Parameter to draw the size of the string , Unit by System.Drawing.Graphics.PageUnit
// Attribute specifies .
//
// abnormal :
// T:System.ArgumentException:
// font by null.
public SizeF MeasureString(string text, Font font);
This method returns SizeF
contain Width
and Height
attribute , Reading these two attributes can get the width and height of the text content ( In pixels ).
//
// Abstract :
// Get or set this System.Drawing.SizeF The horizontal component of the structure .
//
// Return results :
// this System.Drawing.SizeF The horizontal component of the structure , Usually measured in pixels .
public float Width { get; set; }
// Abstract :
// Get or set this System.Drawing.SizeF The vertical component of the structure .
//
// Return results :
// this System.Drawing.SizeF The vertical component of the structure , Usually measured in pixels .
public float Height { get; set; }
So we can first locate according to the upper left corner and lower right corner of the text transmitted from the front , Calculate the rectangular area of the text , Then estimate a font size , Reuse MeasureString
Method calculate the area occupied by the estimated text , Compare with the actual text area size , If it is large, the font will be reduced , If it is small, increase the font . In this way, you can roughly find the appropriate text size .
Concrete realization
- Add text method
/// <summary>
/// Add text to the picture , Text size adaptive
/// </summary>
/// <param name="imgPath"> Picture path </param>
/// <param name="locationLeftTop"> Top left positioning (x1,y1)</param>
/// <param name="locationRightBottom"> Position in the lower right corner (x2,y2)</param>
/// <param name="text"> Written content </param>
/// <param name="fontName"> Font name </param>
/// <returns> After adding text Bitmap object </returns>
public static Bitmap AddText(string imgPath, string locationLeftTop, string locationRightBottom, string text, string fontName = " Chinese Xingkai ")
{
Image img = Image.FromFile(imgPath);
int width = img.Width;
int height = img.Height;
Bitmap bmp = new Bitmap(width, height);
Graphics graph = Graphics.FromImage(bmp);
// Calculate the text area
// top left corner
string[] location = locationLeftTop.Split(',');
float x1 = float.Parse(location[0]);
float y1 = float.Parse(location[1]);
// The lower right corner
location = locationRightBottom.Split(',');
float x2 = float.Parse(location[0]);
float y2 = float.Parse(location[1]);
// Area width and height
float fontWidth = x2 - x1;
float fontHeight = y2 - y1;
float fontSize = fontHeight; // For the first time, the height of the text area is used as the size of the text font , Make adjustments later , Unit is px
Font font = new Font(fontName, fontSize, GraphicsUnit.Pixel);
SizeF sf = graph.MeasureString(text, font);
int times = 0;
// Adjust the font size to fit the text area
if (sf.Width > fontWidth)
{
while (sf.Width > fontWidth)
{
fontSize -= 0.1f;
font = new Font(fontName, fontSize, GraphicsUnit.Pixel);
sf = graph.MeasureString(text, font);
times++;
}
Console.WriteLine(" It was estimated to be big at first , The final font size is {0}, Circulated {1} Time ", font.ToString(), times);
}
else if (sf.Width < fontWidth)
{
while (sf.Width < fontWidth)
{
fontSize += 0.1f;
font = new Font(fontName, fontSize, GraphicsUnit.Pixel);
sf = graph.MeasureString(text, font);
times++;
}
Console.WriteLine(" It was estimated to be small at first , The final font size is {0}, Circulated {1} Time ", font.ToString(), times);
}
// The area occupied by the final font is generally not exactly equal to the actual area
// So according to the difference between the two areas, put the starting position of the text ( Top left positioning ) A little adjustment
x1 += (fontWidth - sf.Width) / 2;
y1 += (fontHeight - sf.Height) / 2;
graph.DrawImage(img, 0, 0, width, height);
graph.DrawString(text, font, new SolidBrush(Color.Black), x1, y1);
graph.Dispose();
img.Dispose();
return bmp;
}
- Test call
private static void Main(string[] args)
{
try
{
DrawingEntity drawing = new DrawingEntity();
Console.WriteLine("Start drawing ...");
System.Drawing.Bitmap bmp = drawing.AddText(@"D:\test\39585148.png", "177.75,63.84", "674.73, 141.6", " The sea , All waves ");
bmp.Save(@"D:\test\output.png");
bmp.Dispose();
Console.WriteLine("Done!");
}
catch (System.Exception ex)
{
Console.WriteLine(" Something went wrong !!\n" + ex.ToString());
}
finally
{
System.Console.WriteLine("\nPress any key to continue ...");
System.Console.ReadKey();
}
}
Final effect :
边栏推荐
- Write a jison parser from scratch (2/10): learn the correct posture of the parser generator parser generator
- 《网络是怎么样连接的》读书笔记 - WEB服务端请求和响应(四)
- Flutter tips: various fancy nesting of listview and pageview
- Service call feign of "micro service"
- 保姆级JDEC增删改查练习
- 法向量点云旋转
- Research and investment strategy report of China's electronic hydrogen peroxide industry (2022 Edition)
- Investment analysis and prospect prediction report of global and Chinese high purity tin oxide Market Ⓞ 2022 ~ 2027
- Global and Chinese market of wheel hubs 2022-2028: Research Report on technology, participants, trends, market size and share
- Write a jison parser from scratch (1/10):jison, not JSON
猜你喜欢
2022-2028 global industrial gasket plate heat exchanger industry research and trend analysis report
How to batch change file extensions in win10
C语言-入门-基础-语法-[运算符,类型转换](六)
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
C language - Introduction - Foundation - syntax - [main function, header file] (II)
C language - Introduction - Foundation - syntax - [identifier, keyword, semicolon, space, comment, input and output] (III)
2022-2028 global edible probiotic raw material industry research and trend analysis report
mmclassification 标注文件生成
HMS core helps baby bus show high-quality children's digital content to global developers
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
随机推荐
《网络是怎么样连接的》读书笔记 - 集线器、路由器和路由器(三)
Get the source code in the mask with the help of shims
20220701 barbarat lemma proof
AMLOGIC gsensor debugging
DR6018-CP01-wifi6-Qualcomm-IPQ6010-IPQ6018-FAMILY-2T2R-2.5G-ETH-port-CP01-802-11AX-MU-MIMO-OFDMA
2022-2028 research and trend analysis report on the global edible essence industry
Global and Chinese markets of thrombography hemostasis analyzer (TEG) 2022-2028: Research Report on technology, participants, trends, market size and share
What is permission? What is a role? What are users?
PMP registration process and precautions
Development trend and market demand analysis report of high purity tin chloride in the world and China Ⓔ 2022 ~ 2027
China electronic grade sulfur trioxide Market Forecast and investment strategy report (2022 Edition)
Write a jison parser from scratch (4/10): detailed explanation of the syntax format of the jison parser generator
Global and Chinese market of planar waveguide optical splitter 2022-2028: Research Report on technology, participants, trends, market size and share
After unplugging the network cable, does the original TCP connection still exist?
"How to connect the network" reading notes - Web server request and response (4)
Reload CUDA and cudnn (for tensorflow and pytorch) [personal sorting summary]
Launchpad x | mode
Research Report on research and investment prospects of China's testing machine industry (2022 Edition)
Global and Chinese markets of hemoglobin analyzers in care points 2022-2028: Research Report on technology, participants, trends, market size and share
How do microservices aggregate API documents? This wave of show~