C# Graphics 繪製文字外框,文字寬度測量

在使用 graphics.DrawString 繪製文字的時候,如果使用同樣的左上角座標繪製矩形,會發現文字往右側偏移,無法對齊。如果自己記錄偏移的寬度,那在不同的文字大小都要各自測試,不然很容易有誤差,也不太聰明。

研究了半天,終於找到解決方式,希望能夠幫助到有需要的人。

程式碼:
  
        this.Paint += (o, e) =>
        {
            using Graphics graphics = e.Graphics;
            var font = new Font("JetBrains Mono", 36, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            graphics.DrawString(text, font, brush, new Point(100, 100), StringFormat.GenericTypographic);
            Size textSize = graphics.MeasureString(text, font, 0, StringFormat.GenericTypographic).ToSize();
            graphics.DrawRectangle(pen, 100, 100, textSize.Width, textSize.Height);
        };
    

但其實只要加上 StringFormat.GenericTypographic 即可讓文字可以往左邊偏移,以我們期望的方式顯示:
  
        this.Paint += (o, e) =>
        {
            using Graphics graphics = e.Graphics;
            var font = new Font("JetBrains Mono", 36);
            graphics.DrawString(text, font, brush, new Point(100, 200), StringFormat.GenericTypographic);
            Size textSize = graphics.MeasureString(text, font, 0, StringFormat.GenericTypographic).ToSize();
            graphics.DrawRectangle(pen, 100, 200, textSize.Width, textSize.Height);
        };
    

執行結果:
(上方為一般繪製,文字會往右側偏移。下方為加上 StringFormat.GenericTypographic 後文字置中)

留言