I want to use custom external font (Monotype Corsiva) as Embedded resource in my Xamarin Forms project. I am using Xamarin.Forms version 4.5.0.617
I got it working, just updated the NuGet package Xamarin.Forms to version 4.5.0.617 in all projects in my Solution.
Previously I had updated Xamarin.Forms NuGet Package to version 4.5x only in the shared project. Hence this error was encountered
System.TypeLoadException: 'Could not load type Xamarin.Forms.ExportFontAttribute'`
Now I have Updated Xamarin.Forms NuGet in all projects (Android, iOS and UWP) in my solution to version 4.5x. Please note that using external custom fonts as Embedded resource in Xamarin Forms requires Xamarin.Forms version 4.5x or later refer to this link for more information
Now the proper way to do it:
Suppose I want to use Monotype Corsiva font in my project and use it as embedded resource.
Update Xamarin.Forms to version 4.5.0.530 or later in all projects in solution (Android, iOS, UWP, etc.). To do it, In Solution Explorer, Right Click Solution name -> Manage NuGet Packages for solution -> Update Xamarin.Forms package to 4.5x or later -> Select all projects and update.
Add a font file (.ttf) in your shared project.
Set the file as Embedded resource (Right Click Font file in Solution Explorer -> Properties -> Build Action: Set as Embedded resource).
Add [assembly: ExportFont("FontFileName.ttf", Alias = "MyFont")]
before any namespace of any class in your project. No need to add full path of the font file. It would be better if you add new class and add the above mentioned code before starting namespace. Just like:
[assembly: ExportFont("MonotypeCorsiva.ttf", Alias = "MyFont")]
namespace MyApplication.Extensions
{
public class ExportFont
{
// You can have an empty class
...
}
}
<Label Text="Hello" FontFamily="MonotypeCorsiva" FontSize="Medium" HorizontalOptions="CenterAndExpand" />
You can use Alias name or Font Name in XAML code. FontFamily = "MyFont"
is also correct.
Now Run the project.
try as following
<Label TextColor="#934293" Text="Swanky" FontSize="80">
<Label.FontFamily>
<OnPlatform x:TypeArguments="x:String">
<On Platform="iOS">Cabin Sketch</On>
<On Platform="Android">CabinSketch-Reg.ttf#Cabin Sketch</On>
</OnPlatform>
</Label.FontFamily>
</Label>