Loading a font in skiasharp

余生长醉 提交于 2021-02-04 19:14:10

问题


How to use a custom font in skiasharp from Xamarin forms.

I tried

paint.Typeface = SKTypeface.FromFamilyName("CoText_Bd"); 

and

paint.Typeface = SKTypeface.FromFile("CoText_Bd");

But both didn't worked out. Do i need to access the path of the font using dependency service ?


回答1:


If you want trully multiplatform solution, put all SkiaSharp/PaintCode drawing Code into .NET standard library, including fonts as embedded resource (Don't forget to set Build action to Embedded resource!). Then you can obtain SKTypeface object using this method (Library ClassLibrary1, Folder Font):

    public static SKTypeface GetTypeface(string fullFontName)
    {
        SKTypeface result;

        var assembly = Assembly.GetExecutingAssembly();
        var stream = assembly.GetManifestResourceStream("ClassLibrary1.Font." + fullFontName);
        if (stream == null)
            return null;

        result = SKTypeface.FromStream(stream);
        return result;
    }

Remeber to Dispose SKObjects when they are not needed anymore.

To optimize perfomance, it is good to cache SKTypeface objects to optimize speed, in Dictionary.

When you put all your drawing code into .NET standard library, you can easy test/develop in Windows Desktop WPF project, enjoy fast compile&build and when you are ready, then use it in mobile app.




回答2:


We should add UIAppFonts in info.plist for iOS

<key>UIAppFonts</key>
<array>
    <string>CoText_Bd.otf</string>
</array>

For Android try

CoText_Bd.otf#CoText_Bd


来源:https://stackoverflow.com/questions/50494804/loading-a-font-in-skiasharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!