Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

c# - PrivateFontCollection Families are not reliable with more iterations

I've load the MemoryStream to a PrivateFontCollection and print the Font-Family count.

I've done these process for 10 times and I want the same output for every iteration. I want correct output for two iterations and sometimes the first iteration is also going wrong. I can't have a consistent output.

Provide me a solution to have a consistent output using PrivateFontCollection.
Note: Fonts folder contains 5 different fonts.

private static void Work()
{
    string fontPath = @"D:fonts";
    PrivateFontCollection fontCollection = null;
    for (int i = 1; i < 11; i++)
    {
        var fileList = Directory.GetFiles(fontPath, "*.ttf", SearchOption.TopDirectoryOnly);
        fontCollection = SafeLoadFontFamily(fileList);
        Console.WriteLine(i+" Iteration and families count:"+fontCollection.Families.Length);
        fontCollection.Dispose();
    }
    Console.ReadKey();
}
private static PrivateFontCollection SafeLoadFontFamily(IEnumerable<string> fontList)
{
    if (fontList == null) return null;
    var fontCollection = new PrivateFontCollection();

    foreach (string fontFile in fontList)
    {
        if (!File.Exists(fontFile)) continue;
        byte[] fontBytes = File.ReadAllBytes(fontFile);
        var fontData = Marshal.AllocCoTaskMem(fontBytes.Length);
        Marshal.Copy(fontBytes, 0, fontData, fontBytes.Length);
        fontCollection.AddMemoryFont(fontData, fontBytes.Length);
    }
    return fontCollection;
}

Expected output for 10 times:
1 Iteration and families count:5
2 Iteration and families count:5
3 Iteration and families count:5
4 Iteration and families count:5
5 Iteration and families count:5
6 Iteration and families count:5
7 Iteration and families count:5
8 Iteration and families count:5
9 Iteration and families count:5
10 Iteration and families count:5

Actual output:[ inconsistent output]
1 Iteration and families count:5
2 Iteration and families count:5
3 Iteration and families count:5
4 Iteration and families count:5
5 Iteration and families count:4
6 Iteration and families count:3
7 Iteration and families count:3
8 Iteration and families count:4
9 Iteration and families count:4
10 Iteration and families count:4

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If all you want to do is to print the name of the Font Family of each Font file stored in a directory, you can simplify your code with something like this.

It orders the Font files by name before printing the Family name.

string fontsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "fonts");
var fontFiles = Directory.GetFiles(fontsPath).OrderBy(s => s).ToList();

fontFiles.ForEach(f => {
    using (var fontCollection = new PrivateFontCollection())
    {
        fontCollection.AddFontFile(f);
        Console.WriteLine(fontCollection.Families[0].Name);
    };
});

If you instead want to preserve the list of the Fonts Family names (for other uses), add each Family name to a List<string> (as a Field, here):

//  As a field
List<string> fontNames = new List<string>();


 // Inside a method
var fontFiles = Directory.GetFiles(fontsPath).ToList();
fontFiles.ForEach(f => {
    using (var fontCollection = new PrivateFontCollection())
    {
        fontCollection.AddFontFile(f);
        fontNames.Add(fontCollection.Families[0].Name);
    };
});
fontNames = fontNames.OrderBy(s => s).ToList();
fontNames.ForEach(familyName => Console.WriteLine(familyName));

Using PrivateFontCollection.AddMemoryFont(). This method can be used for both Font Files and font data from a Font added as a Project Resource (it's just a byte array).

Important: The PrivateFontCollection that these methods return MUST be disposed of in the Form.FormClosing or Form.FormClosed (or where the application's termination is handled).

Call these methods passing a collection of file paths:

// Field/Class object
PrivateFontCollection fontCollection = null;
// (...)
// Somewhere else
string fontsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "fonts");
var fontFiles = Directory.GetFiles(fontsPath);

fontCollection = UnsafeLoadFontFamily(fontFiles);
// Or...
fontCollection = SafeLoadFontFamily(fontFiles);

fontCollection.Families.OrderBy(f => f.Name).ToList().ForEach(font =>
{
    Console.WriteLine(font.GetName(0));
});

Using unsafe mode and a byte* pointer:
(Unsafe code must be enabled in the Project's Properties -> Build panel)

private unsafe PrivateFontCollection UnsafeLoadFontFamily(IEnumerable<string> fontList)
{
    if (fontList.Length == 0) return null;
    var fontCollection = new PrivateFontCollection();

    foreach (string fontFile in fontList)
    {
        if (!File.Exists(fontFile)) continue;
        byte[] fontData = File.ReadAllBytes(fontFile);
        fixed (byte* fontPtr = fontData)
        {
            fontCollection.AddMemoryFont(new IntPtr(fontPtr), fontData.Length);
        }
    }
    return fontCollection;
}

Using Marshal.AllocCoTaskMem() and Marshal.Copy().
Do not call Marshal.FreeCoTaskMem() here. Font curruption may occur. Call PrivateFontCollection.Dispose() instead, as already mentioned.

private PrivateFontCollection SafeLoadFontFamily(IEnumerable<string> fontList)
{
    if (fontList == null) return null;
    var fontCollection = new PrivateFontCollection();

    foreach (string fontFile in fontList)
    {
        if (!File.Exists(fontFile)) continue;
        byte[] fontBytes = File.ReadAllBytes(fontFile);
        var fontData = Marshal.AllocCoTaskMem(fontBytes.Length);
        Marshal.Copy(fontBytes, 0, fontData, fontBytes.Length);
        fontCollection.AddMemoryFont(fontData, fontBytes.Length);
    }
    return fontCollection;
}

Print the Font Collection content:

string fontPath = [The Fonts Path];
PrivateFontCollection fontCollection = null;
for (int i = 0; i < 5; i++) {
    var fileList = Directory.GetFiles(fontPath, "*.ttf", SearchOption.TopDirectoryOnly);
    fontCollection = SafeLoadFontFamily(fileList);
    fontCollection.Families.ToList().ForEach(ff => Console.WriteLine(ff.Name));
    fontCollection.Dispose();
}

System.Windows.Media provides the Fonts.GetFontFamilies() method, just in case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...