0

我正在写一个标尺控件,我想在它下面画一个刻度。不幸的是 WPFs 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);
}
4

1 回答 1

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));
}
于 2012-05-30T09:39:30.827 回答