I need to display words on a WPF Canvas in such a way that they perfectly fit in pre-defined boxes.
One box typically contains a single line of text, from one letter to a few words.
The text inside a box must be as large as possible, i.e: touching all borders of the box (except maybe where it would cause too much text distortion due to abnormal box witdh/height ratio).
I could not find a good way to calculate the appropriate font height, scaling and offset, based on the text content.
A first solution where the original text width/height ratio can’t be changed would already be very nice !
I’d like to use TextBlock elements, but anything else that works should be ok.
As the answer by Robery Levy said, you can use a
Viewboxto achieve this. The text itself won’t stretch however so you’ll still have some “margin” on zero or more sides depending on your text (as you noticed). To work around this you can create a custom control which builds aGeometryfrom aFormattedTextand then draw this withDrawGeometryin OnRender. You’ll notice how the quality of the text improves with a largerFontSize. A very small text (e.g.FontSize="10") won’t look very sharp in a largeViewboxso you’ll have to experiment a bitSome sample Xaml
StretchText.cs