WPF에서 글꼴 크기(FontSize)와 폰트(FontFamily)를 통해 문자열의 크기를 계산하는 방법에 대해 알아보겠습니다.
FormattedText를 사용하여 텍스트의 서식을 지정한 후 크기를 계산할 수 있습니다.
 소스코드
TextBlock 컨트롤을 사용할 경우 다음과 같이 작성하여 문자열의 크기를 구합니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
   | 
 
 
 
  private Size MeasureString(TextBlock textBlock) {     FormattedText formattedText = new FormattedText     (         textBlock.Text,         CultureInfo.CurrentUICulture,         FlowDirection.LeftToRight,         new Typeface         (           textBlock.FontFamily,           textBlock.FontStyle,           textBlock.FontWeight,           textBlock.FontStretch         ),         textBlock.FontSize,         textBlock.Foreground,         VisualTreeHelper.GetDpi(textBlock).PixelsPerDip     );
      return new Size(formattedText.Width, formattedText.Height); }
 
  | 
 
TextBlock 컨트롤을 사용하지 않고 string 문자열과 글꼴 크기, 폰트를 입력하여 길이를 구할 수 있습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
   | 
 
 
 
 
 
  private Size MeasureString(string text, int fontSize, FontFamily fontFamily) {     FormattedText formattedText = new FormattedText     (         text,         CultureInfo.CurrentUICulture,         FlowDirection.LeftToRight,         new Typeface         (             fontFamily,             FontStyles.Normal,             FontWeights.Bold,             FontStretches.Normal         ),         fontSize,         Brushes.Black,         VisualTreeHelper.GetDpi(this).PixelsPerDip     );
      return new Size(formattedText.Width, formattedText.Height); }
 
  | 
 
 사용 방법
TextBlock 컨트롤을 사용할 경우 사용 방법입니다. 
1 2 3 4 5 6 7 8 9 10 11 12
   | TextBlock textBlock = new TextBlock {   Text = "test",   FontFamily = new FontFamily("Arial"),   FontSize = 16,   Foreground = Brushes.Red };
  Size textSize = MeasureString(textBlock);
  Console.Write("Width => " + textSize.Width); Console.Write("Height => " + textSize.Height);
   | 
 
TextBlock 컨트롤을 사용하지 않을 경우 사용 방법입니다. 
1 2 3 4 5 6 7 8
   | string text = "hello eden"; int fontSize = 32; FontFamily fontFamily = new FontFamily("Arial");
  Size textSize = MeasureString(text, fontSize, fontFamily);
  Console.Write("Width => " + textSize.Width); Console.Write("Height => " + textSize.Height);
   | 
 
 참고