How would I make automatic font size scaling with a custom control?
Hi, I'm new to WPF. I've been trying to make an application for the past few days and it's been going quite well so far. I took to StackOverflow to find code for a custom control for a TextBlock but with support for text stroke
https://pastebin.com/CYQVxgpu
However, I'm having an issue trying to make the font size automatically scale to fit the text content within bounds of the control. The text wraps, but I'm trying to make the font size decrease to fit all the text if it is too big, and to increase the font size if the text is too small
In the
UpdateFormattedText
method, I've tried enumerating font sizes from biggest to smallest and finding the maximum font size that contains the text but that didn't work. An interesting behavior with this approach is that the font size is really small like it's at the minimum font size
Any help is appreciatedPastebin
OutlinedTextBlock - Pastebin.com
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
1 Reply
double minFontSize = 4.0;
double maxFontSize = 32.0;
double bestSize = minFontSize;
for (double size = maxFontSize; size >= minFontSize; size -= 0.5)
{
var formattedText = new FormattedText(
yourText,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface(yourFontFamily, yourFontStyle, yourFontWeight, FontStretches.Normal),
size,
Brushes.Black,
new NumberSubstitution(),
1.0);
formattedText.MaxTextWidth = ActualWidth;
formattedText.MaxTextHeight = ActualHeight;
if (formattedText.Width <= ActualWidth && formattedText.Height <= ActualHeight)
{
bestSize = size;
break; // We found a size that fits!
}
}
// Apply the best font size
_FormattedText.SetFontSize(bestSize);