2017-07-26 129 views
1

我們可以很容易地在矩形內繪製文本。C#GDI如何繪製文字以適合矩形?

enter image description here

目前,我想裏面繪製文本和配合的矩形。

enter image description here

請幫助。

+0

究竟是什麼意思擬合?你想讓文字具有與矩形相同的高度和寬度? –

+0

是的,你知道了。文本字符串可以根據該矩形的高度和寬度進行拉伸。 – Paimiya

+0

請發佈您用於第一個版本的代碼,以便人們可以向您展示如何使其適應第二個版本。 – perigon

回答

2

我認爲最簡單的方法是縮放圖形輸出到目標矩形:

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