首页 > 解决方案 > 为什么 Adorner 层无法在 WPF 文本框上正确呈现?

问题描述

我想在 TextBox 的特定文本下绘制波浪线图案。但是在装饰层中没有正确绘制图案。

示例链接: https ://drive.google.com/file/d/1g5148ydo961Hi0A3cA8G3eRnxn8v0arR/view?usp=sharing

在下图中,您可以看到,波浪线图案在许多地方都没有正确渲染。以绿色突出显示的是一些正确渲染的图案。在此处输入图像描述

如果我画了一条也不会正确渲染的简单线。注意下图。以绿色突出显示的是一些正确渲染的线条。 在此处输入图像描述

protected override void OnRender(DrawingContext drawingContext)
    {
        TextBox textBox = this.AdornedElement as TextBox;
        //WordList stores the start index of a word and word as a dictionary collection.
        wordList.Clear();
        // SetRedUnderline method will provide  the wordList which needs to be underline.
        SetRedUnderline(textBox.Text);

        //pathPen is used to draw line with square cap at start and end.
        Pen pathPen = new Pen(new SolidColorBrush(Colors.Red), 0.2);
        pathPen.EndLineCap = PenLineCap.Square;
        pathPen.StartLineCap = PenLineCap.Square;
        //pathGeometry is used to draw segment of wave line by usig BezierSegment.
        Point pathStart = new Point(0, 1);
        BezierSegment pathSegment = new BezierSegment(new Point(1, 0), new Point(2, 2), new Point(3, 1), true);
        PathFigure pathFigure = new PathFigure(pathStart, new PathSegment[] { pathSegment }, false);
        PathGeometry pathGeometry = new PathGeometry(new PathFigure[] { pathFigure });
        //squigglyBrush is customized to darw a tile of pathGeometry. 
        DrawingBrush squigglyBrush = new DrawingBrush();
        squigglyBrush.Viewport = new Rect(0, 0, 6, 4.8);
        squigglyBrush.ViewportUnits = BrushMappingMode.Absolute;
        squigglyBrush.TileMode = TileMode.Tile;
        squigglyBrush.Drawing = new GeometryDrawing(null, pathPen, pathGeometry);
        foreach (KeyValuePair<int, object> keyValuePair in wordList)
        {
            Rect startPosition = textBox.GetRectFromCharacterIndex(keyValuePair.Key);
            Rect endPosition = textBox.GetRectFromCharacterIndex(keyValuePair.Key + keyValuePair.Value.ToString().Length - 1, true);
            Rect rectUnion = Rect.Union(startPosition, endPosition);
            drawingContext.DrawLine(new Pen(squigglyBrush,4), rectUnion.BottomLeft, rectUnion.BottomRight);
            //drawingContext.DrawLine(new Pen(Brushes.Red, 1), rectUnion.BottomLeft, rectUnion.BottomRight);
        }
    }

谢谢..!

标签: c#.netwpf

解决方案


推荐阅读