1

我想在鼠标光标的位置绘制一个文本。因为我需要非常高的性能,所以我想使用GlyphRun。一切正常,但不幸的是我的文字略低于光标。

有人可以帮我修改这种方法以消除这种垂直偏移吗?

现在看起来像这样

我的期望(文字触及光标)

我的代码:

void MyDrawer_MouseMove(object sender, MouseEventArgs e)
{
    Test1();            
}

void Test1()
{
    MyDrawer.DeleteVisual(Dv);
    MyDrawer.Cursor = Cursors.Cross;
    string text = "Hello Word";
    double size = 40;
    Dv = new DrawingVisual();
    using (var dc = Dv.RenderOpen())
    {
        Typeface typeface = new Typeface("Arial");
        if (typeface.TryGetGlyphTypeface(out GlyphTypeface glyphTypeface))
        {
            ushort[] glyphIndexes = new ushort[text.Length];
            double[] advanceWidths = new double[text.Length];

            for (int i = 0; i < text.Length; i++)
            {
                ushort glyphIndex = glyphTypeface.CharacterToGlyphMap[text[i]];
                glyphIndexes[i] = glyphIndex;
                double width = glyphTypeface.AdvanceWidths[glyphIndex] * size;
                advanceWidths[i] = width;
            }

            Point origin = Mouse.GetPosition(MyDrawer);
            //Move text belowe the cursor
            origin = new Point { X = origin.X, Y = origin.Y + (glyphTypeface.Baseline * size) };
            GlyphRun glyphRun = new GlyphRun(glyphTypeface, 0, false, size,
            glyphIndexes, origin, advanceWidths, null, null, null, null,
            null, null);

            dc.DrawGlyphRun(Brushes.Red, glyphRun);
            MyDrawer.AddVisual(Dv);
        }
    }
}

当然,这只是一个测试,实际上不会影响光标,但是指示的点和文本会比这个例子中的要多得多。

4

1 回答 1

2

我在寻找同样的问题时遇到了这个问题。

字形内容(就此而言为 GlyphRun)被包裹在一个黑盒中。
黑盒在顶部包含一些填充。

像这样:字形运行的粗略草图

// To get the box size
var blackBoxHeight = glyphTypeface.Height * fontSize;

// To get the actual character height
var characterHeight = glyphTypeface.Baseline * fontSize;

// To get the padding inside the black box
var blackBoxPadding = blackBoxHeight - characterHeight;

// set the point to draw a little bit up (skip the padding)
origin.Y -= blackBoxPadding;

// Create the glyph
var run = new GlyphRun
            (
                glyphTypeface: glyphTypeface,
                bidiLevel: 0,
                isSideways: false,
                renderingEmSize: fontSize,
                pixelsPerDip: 1.0f,
                glyphIndices: indices,
                baselineOrigin: origin, /* The point containing the padding offset */
                advanceWidths: widths,
                glyphOffsets: null,
                characters: null,
                deviceFontName: null,
                clusterMap: null,
                caretStops: null,
                language: null
            );
于 2020-09-22T11:18:50.463 回答