2009-05-05 42 views
13

Tôi đã sử dụng TextRenderer để Đo chiều dài của một chuỗi và do đó kích thước một điều khiển phù hợp. Có tương đương trong WPF hay tôi chỉ có thể sử dụng TextRendered.MeasureString?WPF tương đương với TextRenderer

Trả lời

3

Hãy nhìn vào các FormattedText class

Nếu bạn cần kiểm soát chi tiết hơn, sau đó bạn cần phải đi xuống để AdvanceWidths viên kiểu GlyphTypeface của. Tìm thấy một similar discussion ở đây với đoạn mã trông giống như nó có thể hoạt động.

Cập nhật: Có vẻ như đây có thể trùng lặp với Measuring text in WPF .. OP vui lòng xác nhận.

18

Cảm ơn Gishu,

Reading liên kết của bạn tôi đã đưa ra những điều sau cả hai đều làm công việc cho tôi:

/// <summary> 
    /// Get the required height and width of the specified text. Uses FortammedText 
    /// </summary> 
    public static Size MeasureTextSize(string text, FontFamily fontFamily, FontStyle fontStyle, FontWeight fontWeight, FontStretch fontStretch, double fontSize) 
    { 
     FormattedText ft = new FormattedText(text, 
              CultureInfo.CurrentCulture, 
              FlowDirection.LeftToRight, 
              new Typeface(fontFamily, fontStyle, fontWeight, fontStretch), 
              fontSize, 
              Brushes.Black); 
     return new Size(ft.Width, ft.Height); 
    } 

    /// <summary> 
    /// Get the required height and width of the specified text. Uses Glyph's 
    /// </summary> 
    public static Size MeasureText(string text, FontFamily fontFamily, FontStyle fontStyle, FontWeight fontWeight, FontStretch fontStretch, double fontSize) 
    { 
     Typeface typeface = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch); 
     GlyphTypeface glyphTypeface; 

     if(!typeface.TryGetGlyphTypeface(out glyphTypeface)) 
     { 
      return MeasureTextSize(text, fontFamily, fontStyle, fontWeight, fontStretch, fontSize); 
     } 

     double totalWidth = 0; 
     double height = 0; 

     for (int n = 0; n < text.Length; n++) 
     { 
      ushort glyphIndex = glyphTypeface.CharacterToGlyphMap[text[n]]; 

      double width = glyphTypeface.AdvanceWidths[glyphIndex] * fontSize; 

      double glyphHeight = glyphTypeface.AdvanceHeights[glyphIndex]*fontSize; 

      if(glyphHeight > height) 
      { 
       height = glyphHeight; 
      } 

      totalWidth += width; 
     } 

     return new Size(totalWidth, height); 
    } 
Các vấn đề liên quan