在尖锐的dx中找到GlyphRun的宽度

时间:2013-01-08 04:10:01

标签: c# text directx sharpdx letter-spacing

我无法使用锐利的DX计算glyphRun的宽度。下面是我用来渲染glyphRun的代码,字符串需要呈现为char,如下所示。

private void RenderGlyphRun(FontFace fontFace)
    {
        GlyphRun glyphRun = new GlyphRun();
        glyphRun.FontFace = fontFace;
        glyphRun.FontSize = 23;
        left = 50;
        top = 50;

        string word = "Hello World";
        foreach (char letter in word)
        {
            string stringToBeRendered = letter.ToString();
            int[] codePoints = new int[stringToBeRendered.Length];

            char[] charsToBeRendered = stringToBeRendered.ToCharArray();
            for (int i = 0; i < charsToBeRendered.Length; i++)
            {
                codePoints[i] = (int)charsToBeRendered[i];
            }
            short[] glyphIndices = fontFace.GetGlyphIndices(codePoints);

            glyphRun.Indices = glyphIndices;
            var BrushColor = SharpDX.Color.Black;

            SharpDX.DirectWrite.Matrix mtrx = new SharpDX.DirectWrite.Matrix();
            mtrx.M11 = 1F;
            mtrx.M12 = 0;
            mtrx.M21 = 0;
            mtrx.M22 = 1F;
            mtrx.Dx = 0;
            mtrx.Dy = 0;

            GlyphMetrics[] metrics = fontFace.GetGdiCompatibleGlyphMetrics(23, 1, mtrx, false, glyphIndices, false);

            FontMetrics metr = fontFace.GetGdiCompatibleMetrics(23, 1, new SharpDX.DirectWrite.Matrix());
            _pRenderTarget.DrawGlyphRun(new SharpDX.DrawingPointF(left, top), glyphRun, new SharpDX.Direct2D1.SolidColorBrush(_pRenderTarget, BrushColor), MeasuringMode.GdiClassic);

            left += (metrics[0].AdvanceWidth - metrics[0].RightSideBearing + metrics[0].LeftSideBearing) / 100;                
        }
    }

渲染字符串中字符的间距非常不同。请帮帮我。

2 个答案:

答案 0 :(得分:2)

@suresh,

您可以在 glyphRun 中计算每个字形宽度,如下所示

clusterwidth=glyphRun.glyphRun.Advances[Index]

基于此,您可以计算总 glyphRun 宽度,如下所示

for(int i=0; i<glyphRun.Indices.Length; i++)
{
totalWidth+=glyphRun.Advances[i];
}

答案 1 :(得分:1)

+1给pashaplus指出我正确的方向。

我需要做同样的事情,我使用一个简单的LINQ表达式得到这样的总和。

var glyphRunWidth = drawing.GlyphRun.AdvanceWidths.Sum(a => a);