简体   繁体   English

C#GDI如何绘制文本以适合矩形?

[英]C# GDI How to draw text to fit in rectangle?

We can draw a text inside a rectangle easily. 我们可以轻松地在矩形内绘制文本。

在此处输入图片说明

Currently I would like to draw a text inside and FIT a rectangle. 目前,我想在其中绘制文本,然后将其设置为矩形。

在此处输入图片说明

Please help. 请帮忙。

I think the easiest way is to scale the graphics output to the destination rectangle: 我认为最简单的方法是将图形输出缩放到目标矩形:

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM