Skip to content

Commit

Permalink
[Android] Allow to use system fonts (#15010)
Browse files Browse the repository at this point in the history
  • Loading branch information
jsuarezruiz committed May 19, 2023
1 parent 3454314 commit 46e02ac
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/Core/src/Fonts/FontManager.Android.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Concurrent;
using System.IO;
using Android.Graphics;
using Android.Graphics.Fonts;
using Android.Util;
using Microsoft.Extensions.Logging;
using AApplication = Android.App.Application;
Expand Down Expand Up @@ -130,6 +131,22 @@ public FontSize GetFontSize(Font font, float defaultFontSize = 0)
return null;
}

Typeface? LoadDefaultTypeface(string fontfamily)
{
switch (fontfamily.ToLowerInvariant())
{
case "monospace":
return Typeface.Monospace;
case "sansserif":
case "sans-serif":
return Typeface.SansSerif;
case "serif":
return Typeface.Serif;
default:
return null;
}
}

Typeface? CreateTypeface((string? fontFamilyName, FontWeight weight, bool italic) fontData)
{
var (fontFamily, weight, italic) = fontData;
Expand All @@ -140,7 +157,9 @@ public FontSize GetFontSize(Font font, float defaultFontSize = 0)

if (!string.IsNullOrWhiteSpace(fontFamily))
{
if (GetFromAssets(fontFamily) is Typeface typeface)
if (LoadDefaultTypeface(fontFamily) is Typeface systemTypeface)
result = systemTypeface;
else if (GetFromAssets(fontFamily) is Typeface typeface)
result = typeface;
else
result = Typeface.Create(fontFamily, style);
Expand Down
16 changes: 16 additions & 0 deletions src/Core/tests/DeviceTests/Services/FontManagerTests.Android.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,20 @@ public void CanLoadEmbeddedFont()

Assert.False(expected.Equals(actual));
}

[Theory]
[InlineData("monospace")]
[InlineData("sansserif")]
[InlineData("serif")]
public void CanLoadSystemFonts(string fontName)
{
if (!OperatingSystem.IsAndroidVersionAtLeast(28))
return;

var registrar = new FontRegistrar(fontLoader: null);
var manager = new FontManager(registrar);
var actual = manager.GetTypeface(Font.OfSize(fontName, 12));

Assert.NotEqual(Typeface.Default, actual);
}
}

0 comments on commit 46e02ac

Please sign in to comment.