Loading a font in skiasharp
Asked Answered
G

2

6

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 ?

Ganger answered 23/5, 2018 at 18:7 Comment(0)
K
13

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.

Kyanite answered 24/5, 2018 at 18:57 Comment(2)
There is a reason to use the native resource management: embedded resources bloat the assembly and may make loading times longer. Also, native resources can be localized or optimized by the OS.Fluted
I got the point, but having out of the box multiplatform is nice one too. And also fonts are not localized and with good management they are loaded only once. But would be nice to have some benchmark of approaches - app size + startup speed.Kyanite
R
1

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
Remunerative answered 23/5, 2018 at 19:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.