Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silverlight : How to predict string size?

I'm facing a lot of problem with Silverlight way to deal with layout. Mainly, I can't find a way to predict the size occupied by strings before they are actually drawn. On iPhone, we have some very simple methods that allow us to determine the size a string will occupy on screen based on font size, word wrapping option and available width and/or height. But with Silverlight, I can't find a way to have consistent results across my app.

I'm currently using the ActuelHeight and ActualWidth of a TextBlock instance but it gives me random results. For instance, I a use the following code...

TextBlock proto = new TextBlock();

proto.Width = 456;
proto.TextWrapping = TextWrapping.Wrap;
proto.Text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
double h = proto.ActualHeight;

...h is set to 66 pixels ! As you can guess by yourself, there is no way such a long text could fit on a rectangle of 456 pixels wide and 66 pixels high. And it is confirmed when I add the text block inside a canvas, set its size to {456;66} and test the app : the text doesn't fit on the text block at all !

Can someone explain me where the problem lies and point me to a consistent (and trustable) way to measure string sizes ?

Thanks by advance,

Eric.

like image 437
Eric MORAND Avatar asked Nov 07 '10 13:11

Eric MORAND


Video Answer


1 Answers

You can ask the TextBlock to measure itself (without it yet being displayed) by calling its Measure method:

textBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
var width = textBlock.DesiredSize.Width;
var height = textBlock.DesiredSize.Height;

Of course, it may not have infinite width and height, so depending on your use case you may prefer to ask your root element to measure itself, which will in turn measure all children (including the TextBlock).

like image 72
Kent Boogaart Avatar answered Sep 22 '22 15:09

Kent Boogaart