C# GDI 如何绘制适合矩形的文本?
C# GDI How to draw text to fit in rectangle?
我们可以轻松地在矩形内绘制文本。
目前我想在里面画一个文字,然后FIT一个矩形。
请帮忙。
我认为最简单的方法是将图形输出缩放到目标矩形:
public static class GraphicsExtensions
{
public static void DrawStringInside(this Graphics graphics, Rectangle rect, Font font, Brush brush, string text)
{
var textSize = graphics.MeasureString(text, font);
var state = graphics.Save();
graphics.TranslateTransform(rect.Left, rect.Top);
graphics.ScaleTransform(rect.Width / textSize.Width, rect.Height / textSize.Height);
graphics.DrawString(text, font, brush, PointF.Empty);
graphics.Restore(state);
}
}
我们可以轻松地在矩形内绘制文本。
目前我想在里面画一个文字,然后FIT一个矩形。
请帮忙。
我认为最简单的方法是将图形输出缩放到目标矩形:
public static class GraphicsExtensions
{
public static void DrawStringInside(this Graphics graphics, Rectangle rect, Font font, Brush brush, string text)
{
var textSize = graphics.MeasureString(text, font);
var state = graphics.Save();
graphics.TranslateTransform(rect.Left, rect.Top);
graphics.ScaleTransform(rect.Width / textSize.Width, rect.Height / textSize.Height);
graphics.DrawString(text, font, brush, PointF.Empty);
graphics.Restore(state);
}
}