キャンバスに描画されるテキストの幅と高さを測る - 文字列の幅と高さの計算 - C#
キャンバスに描画されるテキストの幅と高さを取得するコードを紹介します。
概要
C#でキャンバスに文字を描画する際に事前に描画されるテキストの幅や高さを取得したい場合があります。
GraphicsオブジェクトのMeasureString()メソッドを用いると描画されるテキストの幅、高さを取得できます。
プログラム例
UI
下図のUIを準備します。
コード
以下のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GraphicsDemo
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
string text="ABCDEFG";
e.Graphics.DrawString(text, this.Font, new SolidBrush(Color.Black), new PointF(10,10));
e.Graphics.PageUnit = GraphicsUnit.Pixel;
SizeF sizef = e.Graphics.MeasureString(text, this.Font);
e.Graphics.DrawString(Convert.ToString(sizef.Width), this.Font,
new SolidBrush(Color.Black), new PointF(10, 64));
e.Graphics.DrawString(Convert.ToString(sizef.Height), this.Font,
new SolidBrush(Color.Black), new PointF(10, 84));
}
}
}
解説
"ABCDEFG"の文字をpanel1のキャンバスに描画します。
下記のコードで、画面に文字列を描画します。
string text="ABCDEFG";
e.Graphics.DrawString(text, this.Font, new SolidBrush(Color.Black), new PointF(10,10));
以下のコードが描画テキストの幅と高さを取得するコードです。MeasureString()メソッドでテキストの幅と高さを取得できます。
第二引数には描画に使うフォントを指定します。
e.Graphics.PageUnit = GraphicsUnit.Pixel;
SizeF sizef = e.Graphics.MeasureString(text, this.Font);
実行結果
実行すると下図の画面が表示されます。画面に描画されている"ABCDEFG"の文字列の幅と高さが画面に表示されます。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用