1
votes

I am working in native xamarin andorid. I am facing issue to set custom font. I am using "SkiaSharp" plugin to generate canvas view. That plugin is inside PCL so that can be use in both android and ios.

I have one .ttf file in my "Assets" folder.

I generate font path using following code.

string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string FontPath = System.IO.Path.Combine(path, "Myfile.ttf");

this Path I send to PCL to set "SKTypeface"

paint.Typeface = SKTypeface.FromFile(FontPath, 0);

if it is "Typeface" then I can use following approach

Typeface tf = Typeface.CreateFromAsset(Assets, "Myfile.ttf");

I always get null SKTypeface as return value.

I think font path is not found.

bool flag=File.Exist(FontPath)

it always return null value.

How to get path of Asset folder in xamarin andorid? How to set custom font to SKTypeface?

1
paint.Typeface = SKTypeface.FromFamilyName("Arial"); its working but custom font not workingRMR

1 Answers

3
votes

You typically don't use the path for the android assets as they are located inside the app package. Rather you get a stream and load that - however asset streams are not seekable, so they have to be copied first:

SKTypeface typeface;
using (var asset = Assets.Open("Fonts/CONSOLA.TTF"))
{
    var fontStream = new MemoryStream();
    asset.CopyTo(fontStream);
    fontStream.Flush();
    fontStream.Position = 0;
    typeface = SKTypeface.FromStream(fontStream);
}

...
paint.Typeface = typeface;

I also want to make a note that this is relatively "slow" so you probably want to do this once and then just re-use the typeface. Avoid loading files directly in the paint methods as the paint happens on the UI thread and will block.

When loading assets, do not include the root "Assets" folder as this is assumed.

EDIT

In the new v1.59.2 release, the existing FromStream method will work as expected, regardless of the stream.