Programmatically measure text string in pixels for Silverlight
Asked Answered
R

1

17

In WPF there is the FormattedText in the System.Windows.Media namespace MSDN FormattedText that I can use like so:

private static Size GetTextSize(string txt, string font, int size, bool isBold)
{
   Typeface tf = new Typeface(new System.Windows.Media.FontFamily(font),
                             FontStyles.Normal,
                             (isBold) ? FontWeights.Bold : FontWeights.Normal,
                             FontStretches.Normal);
   FormattedText ft = new FormattedText(txt, new CultureInfo("en-us"), System.Windows.FlowDirection.LeftToRight, tf, (double)size, System.Windows.Media.Brushes.Black, null, TextFormattingMode.Display);
   return new Size { Width = ft.WidthIncludingTrailingWhitespace, Height = ft.Height };
}

Is there a good approach in Silverlight to getting the width in pixels (at the moment height isn't important) besides making a call to the server?

Resee answered 4/2, 2011 at 16:23 Comment(0)
H
30

An approach that I've seen used, that may not work in your particular instance, is to throw the text into an unstyled TextBlock, and then get the width of that control, like so:

private double GetTextWidth(string text, int fontSize)
{
    TextBlock txtMeasure = new TextBlock();
    txtMeasure.FontSize = fontSize;
    txtMeasure.Text = text;
    double width = txtMeasure.ActualWidth;
    return width;
}

It's a hack, no doubt.

Haldan answered 4/2, 2011 at 16:34 Comment(2)
+1, but remember to invalidate measure and arrange before getting the actual width.Demesne
Unfortunately, this solution has small margins above and below the actual text.Auburta

© 2022 - 2024 — McMap. All rights reserved.