1. 소스
/// <summary>
/// 컨트롤에 들어갈 문자열의 폭과 높이를 구한다.
/// </summary>
/// <param name="str">문자열</param>
/// <param name="ctrl">컨트롤</param>
/// <returns>폭과 높이</returns>
static public SizeF GetStringSize(string str, Control ctrl)
{
try
{
float wi = float.MinValue, hi;
Font font = ctrl.Font;
Bitmap tmpBit = new Bitmap(1, 1);
Graphics graphic = Graphics.FromImage(tmpBit);
Brush TextColor = Brushes.Black;
graphic.DrawString(str, font, TextColor, new PointF(0, 0), StringFormat.GenericDefault);
var size = graphic.MeasureString(str, font, 1500, StringFormat.GenericTypographic);
hi = size.Height;
size.Width += 10;
if (size.Width > wi)
wi = size.Width;
else
KLog.Write("컨트롤에 들어갈 문자열의 크기를 구하지 못했습니다.");
return new SizeF(wi, hi);
}
catch (Exception ex)
{
KLog.Write(ex.ToString());
}
KLog.Write("컨트롤에 들어갈 문자열의 크기를 구하지 못했습니다.");
return SizeF.Empty;
}
2. 사용 예제
void SetUserText(string text)
{
try
{
UserText = text;
LBL_TEXT.Text = UserText;
var sz = FuncsOfCtrl.GetStringSize(UserText, LBL_TEXT);
TextLen = (int)sz.Width;
}
catch (Exception ex)
{
KLog.Write(ex.ToString());
}
}
'유용한 정보' 카테고리의 다른 글
[C#] 문자열을 속성으로 갖는 클래스 만들기 (0) | 2025.04.16 |
---|---|
[C#] INI Parser (0) | 2025.04.16 |
[C#] 컨트롤에 들어갈 문자열에서 가장 큰 폭과 높이 구하기 (0) | 2025.04.16 |
[C#] DataGridView 에 수직스크롤바가 있는지의 여부 판단하기 (0) | 2025.04.16 |
[C#] DataGridView 의 RowHeader 에 일련번호 자동생성하기 (0) | 2025.04.16 |