I am using FormattedText to display text. I need to align the text horizontally as per options provided. Everything works fine till I set the "MaxTextWidth" property(I need this for word trimming). How do I align the text along with word trimming enabled?
FormattedText formatted_text = new FormattedText(
text, System.Globalization.CultureInfo.GetCultureInfo("en-US"),
FlowDirection.LeftToRight,
typeface, em_size, brush);
formatted_text.TextAlignment = TextAlignment.Right;
drawingContext.DrawText(formatted_text, origin);
This works fine aligning the code as expected. But I need to trim the word w.r.t MaxTextWidth. I run into issues in setting MaxTextWidth. How do I calculate MaxTextWidth?
The point in the image is the origin.
This is what I get when I dont set MaxTextWidth


This when I set MaxTextWidth = 100
How do I calculate MaxTextWidth so I can align the trimmed sentence?
Edit: Adding more screenshots

Before setting MaxTextWidth, properly aligned, After setting
I lose the word alignment, look w.r.t the reference point shown
It is a strange behavior of
DrawingContext.DrawText
that MaxTextWidth
has an effect on origin.
If FormattedText is right aligned and MaxTextWidth = 0, i.e. default, DrawText puts the
text left of origin. If MaxTextWidth > 0, DrawText puts the text right of origin.
Hence you have to substract MaxTextWidth from origin.X if right aligned
and the half if centered. Here is an example. Blue dots are the desired origins and red ones the corrected.

using System.Windows;
using System.Windows.Media;
public void DrawTextTest(DrawingContext dc) {
var y = 100.0;
foreach (var align in new TextAlignment[]{
TextAlignment.Left, TextAlignment.Center, TextAlignment.Right}) {
foreach (var width in new double[] { 0.0, 150.0 }) {
DrawText(dc, new Point(400, y), align, width);
y += 25.0;
}
y += 45.0;
}
}
private void DrawText(DrawingContext dc, Point origin,
TextAlignment align, double maxTextWidth) {
var f = new FormattedText(
"This is a text with TextAlignment = " + align.ToString()
+ " and MaxTextWidth = " + maxTextWidth.ToString() + ".",
System.Globalization.CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface("Arial"), 12.0, Brushes.Black
) {
TextAlignment = align,
MaxTextWidth = maxTextWidth
};
dc.DrawEllipse(Brushes.Blue, null, origin, 1.0, 1.0);
var correctionX = -maxTextWidth * (align == TextAlignment.Right ? 1.0
: (align == TextAlignment.Center ? 0.5 : 0.0));
origin.Offset(correctionX, 0.0);
dc.DrawEllipse(Brushes.Red, null, origin, 1.0, 1.0);
dc.DrawText(f, origin);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With