xamarin.formsxamarin.androidxamarin.iosskiasharpmapsui

How to get SKTypeface.FromFamilyName to return a font for Japanese, Korean, Chinese (Android + iOS, Xamarin.Forms)


I'm using a library that uses SKTypeface.FromFamilyName internally to render font on the screen. However, as I found out if the text to display is japanese, korean or chinese, it just prints squares. I tried to add a custom font to my project but I was not able to make SKTypeface.FromFamilyName return anything but NULL with custom fonts. As I have no access to change SKTypeface.FromFamilyName to something else ( at least as far as I know because it's in a private method of a static class - https://github.com/Mapsui/Mapsui/blob/5008d3ab8b0453c27cb487fe6ad3fac87435abbe/Mapsui.Rendering.Skia/LabelRenderer.cs#L277 ), is there any way I can make it return any font for each language (or one per language) that works with these?


Solution

  • Alright, I found a solution for this. This seems to work for me:

    string fontFamily;
    switch (Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName.ToLower())
    {
        case "ja":
            fontFamily = SKFontManager.Default.MatchCharacter('あ').FamilyName;
            break;
    
        case "ko":
            fontFamily = SKFontManager.Default.MatchCharacter('매').FamilyName;
            break;
    
        case "zh":
            fontFamily = Thread.CurrentThread.CurrentUICulture.IetfLanguageTag.ToLower() switch
                {
                    "zh-cn" => SKFontManager.Default.MatchCharacter('实').FamilyName,
                    "zh-tw" => SKFontManager.Default.MatchCharacter('實').FamilyName,
                    _ => null
                };
            break;
    
        default:
            fontFamily = null;
            break;
    }