Question

I'm using DrawText to draw FormattedText on Visual Layer. Now I'm using the code below to define the formatted text and I'm able to set the TextAlignment to Center. But what about the VerticalAlignment? As you can see in the image below the center of the text is not on the centerpoint which is shown with a red dot here.

The part where I'm defining the FormattedText :

var ft = new FormattedText("A",
    CultureInfo.GetCultureInfo("en-us"),
    FlowDirection.LeftToRight,
    new Typeface("Verdana"),
    36, Brushes.Yellow);

ft.TextAlignment = TextAlignment.Center;

The part where I'm drawing the text:

var centerpoint = new Point(0,0);
dc.DrawText(ft, centerpoint);

Here is final result:

enter image description here

I want the middle of the text to lie on the center of the circle.

Was it helpful?

Solution

Well Ok it seems I was able to solve this. It is not that hard. I'll post the answer here for future reference. And It might help other people too.

As it seems there is not such a thing as VerticalAlignment for a FormattedText so we need to calculate and position it ourselves. Since we can get the Height property of the formatted text. We can easily align the text like this:

dc.DrawText(ft, new Point(centerpoint.X, centerpoint.Y- ft.Height/2));

Here is the result

OTHER TIPS

Last version of FormattedText with PixelsPerDip.

Typeface typeFace = new Typeface(new FontFamily("Segoe UI"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
FormattedText formattedText = new FormattedText("Bodrum Bodrum", CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, typeFace, 14, Brushes.Black, VisualTreeHelper.GetDpi(this).PixelsPerDip);

Point textPoint = new Point(100, 100);
drawingContext.DrawText(formattedText, textPoint);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top