Exemplo n.º 1
0
        public SpriteFont(FontSize fontSize, TextureFilter filter = TextureFilter.Linear)
        {
            FamilyName = fontSize.Font.FamilyName;
            StyleName  = fontSize.Font.StyleName;
            Size       = fontSize.Size;
            Ascent     = fontSize.Ascent;
            Descent    = fontSize.Descent;
            LineGap    = fontSize.LineGap;
            Height     = fontSize.Height;
            LineHeight = fontSize.LineHeight;

            var packer = new Packer();
            {
                var bufferSize = (fontSize.Size * 2) * (fontSize.Size * 2);
                var buffer     = (bufferSize <= 16384 ? stackalloc Color[bufferSize] : new Color[bufferSize]);

                foreach (var ch in fontSize.Charset.Values)
                {
                    var name = ch.Unicode.ToString();

                    // pack bmp
                    if (fontSize.Render(ch.Unicode, buffer, out int w, out int h))
                    {
                        packer.AddPixels(name, w, h, buffer);
                    }

                    // create character
                    var sprChar = new Character(ch.Unicode, new Subtexture(), new Vector2(ch.OffsetX, ch.OffsetY), ch.Advance);
                    Charset.Add(ch.Unicode, sprChar);

                    // get all kerning
                    foreach (var ch2 in fontSize.Charset.Values)
                    {
                        var kerning = fontSize.GetKerning(ch.Unicode, ch2.Unicode);
                        if (Math.Abs(kerning) > 0.000001f)
                        {
                            sprChar.Kerning[ch2.Unicode] = kerning;
                        }
                    }
                }

                packer.Pack();
            }

            // link textures
            var output = packer.Pack();

            if (output != null)
            {
                for (int i = 0; i < output.Pages.Count; i++)
                {
                    var texture = new Texture(output.Pages[i]);
                    texture.Filter = filter;

                    foreach (var entry in output.Entries.Values)
                    {
                        if (entry.Page != i)
                        {
                            continue;
                        }

                        if (Charset.TryGetValue(entry.Name[0], out var character))
                        {
                            character.Image.Reset(texture, entry.Source, entry.Frame);
                        }
                    }
                }
            }
        }