簡體   English   中英

C#GDI如何繪制文本以適合矩形?

[英]C# GDI How to draw text to fit in 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