mono / libgdiplus

C-based implementation of the GDI+ API
http://www.mono-project.com/
MIT License
329 stars 171 forks source link

Grouped fonts with same family #693

Open trungnt2910 opened 3 years ago

trungnt2910 commented 3 years ago

This should fix #692.

I've changed GpFontFamily implementation, so that it keeps tracks of all fonts of the same family. I've also changed FontFamily functions so that they handle style properly like they should on Windows.

This code should work correctly after applying fix:

            fontCollection = new PrivateFontCollection();

            var resourceNames = Assembly.GetExecutingAssembly().GetManifestResourceNames()
                .Where((name) => name.StartsWith("UI.Fonts.OpenSans"));

            foreach (var resoureName in resourceNames)
            {
                var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resoureName);
                var fontData = new byte[stream.Length];
                stream.Read(fontData, 0, (int)stream.Length);
                stream.Dispose();

                var fontPtr = Marshal.AllocCoTaskMem(fontData.Length);
                Marshal.Copy(fontData, 0, fontPtr, fontData.Length);
                fontCollection.AddMemoryFont(fontPtr, fontData.Length);
                Marshal.FreeCoTaskMem(fontPtr);
            }

            Light = fontCollection.Families.FirstOrDefault(font => font.Name == "Open Sans Light");
            Regular = fontCollection.Families.FirstOrDefault(font => font.Name == "Open Sans");
            ExtraBold = fontCollection.Families.FirstOrDefault(font => font.Name == "Open Sans ExtraBold");
            SemiBold = fontCollection.Families.FirstOrDefault(font => font.Name == "Open Sans SemiBold");

            System.Windows.Forms.MessageBox.Show(string.Join("\n", fontCollection.Families.Select(f => f.Name)));
            Preview(new Font(Regular, 72, FontStyle.Bold | FontStyle.Italic), "ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^");

Before applying fix, with build from head of master: On my Ubuntu 20.04 with latest mono, the library seems to pick a random style: This is output from multiple runs: First run: image Second run: Screenshot from 2021-02-09 22-29-15

After applying fix, the correct style (Bold Itatlic) is applied: Screenshot from 2021-02-09 22-35-27