suresh
suresh

Reputation: 177

Finding width of the GlyphRun in sharp dx

I could not manage to calculate the width of the glyphRun using the sharp DX. Below is the code I use to render the glyphRun and the string needs to be rendered as char as below.

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

the spacing of the characters in the rendered string is very different. Please help me with this.

Upvotes: 1

Views: 715

Answers (2)

Brad Cunningham
Brad Cunningham

Reputation: 6501

+1 to pashaplus for pointing me in the right direction.

I needed to do the same thing and I used a simple LINQ expression to get the sum like this.

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

Upvotes: 1

pashaplus
pashaplus

Reputation: 3716

@suresh,

you can calculate each glyph Width in glyphRun like below

clusterwidth=glyphRun.glyphRun.Advances[Index]

based on this you can calculate total glyphRun Width like below

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

Upvotes: 2

Related Questions