How to measure rendered string dimensions in #Win8Dev

While Windows 8 WinRT supports ViewBox control (its a control that allows text to auto resize depending upon available space), with my alarm clock app, I noticed substantial jittering (and resizing) as time changes between seconds. Of course you don’t want that happening.

The solution is to find optimum font size at start and then sticking with it until a resize is desired. Once you set the font family and font size to a textblock (tb), you can try getting its height / width.

With Windows Phone, the following would work well

this.tb.FontSize = 20;
double currentWidth = this.tb.ActualWidth;
double currentHeight = this.tb.ActualHeight;

This however does not work with Windows 8 / WinRT API. Here’s what you need to do

this.tb.FontSize = 20;
this.tb.Measire(new Size(400, 300)); // assuming that 400x300 is max size of textblock you want
double currentWidth = this.tb.DesiredSize.Width;
double currentHeight = this.tb.DesiredSize.Height;

Thats it really. I tend to increase / decrease font size depending upon need and only recalculated it if user wants a different font or changes the view (ie default to snapped etc)

About these ads

2 thoughts on “How to measure rendered string dimensions in #Win8Dev

  1. Pingback: Windows 8: How to measure rendered string dimensions | azkafaiz.com

  2. Pingback: Windows 8 Developer Links – 2012-09-20Dan Rigby | Dan Rigby

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s