I a writing a ruler control and I want to draw a scale beneath it. Unfortunately WPFs DrawingContext.DrawText method (although it gets invoked) doesn’t draw anything. Did anybody have the same problem and knows a solution? This is the part of the code where the text gets rendered:
protected void RenderRulerScale(DrawingContext drawingContext)
{
int value = 0;
for (double x = this.LargeUnit * (this.ActualWidth / this.Maximum);
x < this.ActualWidth; x += this.LargeUnit * (this.ActualWidth / this.Maximum))
{
string unitString = (++value).ToString() + this.UnitName;
FormattedText formattedUnitString = new FormattedText(unitString,
new CultureInfo("en-US"), FlowDirection.LeftToRight,
new Typeface("Arial"), 5.0, Brushes.Black)
{
TextAlignment = TextAlignment.Center,
MaxTextWidth = 2 * this.LargeUnit,
MaxTextHeight = 25.0
};
drawingContext.DrawText(formattedUnitString, new Point(x, (2.0 / 3.0) *
this.ActualHeight));
}
}
This method is called in the OnRender method:
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
this.RenderRulerScale(drawingContext);
}
I finally found the solution! I think the problem was the text alignment. I set it back to left and it just worked. Here is the code: