WPF不会绘制DrawingContext.DrawText

时间:2012-05-25 12:12:56

标签: wpf text drawing controls render

我写了一个标尺控件,我想在它下面画一个刻度。不幸的是,WPF的DrawingContext.DrawText方法(虽然它被调用)不会绘制任何东西。有人有同样的问题,知道解决方案吗?这是呈现文本的代码的一部分:

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));
    }
}

在OnRender方法中调用此方法:

protected override void OnRender(DrawingContext drawingContext)
{
    base.OnRender(drawingContext);
    this.RenderRulerScale(drawingContext);
}

1 个答案:

答案 0 :(得分:0)

我终于找到了解决方案!我认为问题是文本对齐。我把它设置回左边,它只是工作。这是代码:

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,
        Thread.CurrentThread.CurrentUICulture, FlowDirection.LeftToRight,
        new Typeface(new FontFamily("Arial"), FontStyles.Normal, FontWeights.Normal,
        FontStretches.Normal) , 10.0, Brushes.Black);
    drawingContext.DrawText(formattedUnitString,
        new Point(x - (formattedUnitString.Width / 2.0), (2.0 / 3.0) *
        this.ActualHeight));
}