유용한 정보

[C#] 컨트롤에 들어갈 문자열의 폭과 높이 구하기

DevReff 2025. 4. 16. 05:21
728x90
728x90
SMALL

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

728x90
728x90
LIST