How to get path of font file from asset folder and how to use that path to set SKTypeface in xamarin android?

邮差的信 提交于 2019-12-11 06:08:02

问题


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:


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.



来源:https://stackoverflow.com/questions/46538300/how-to-get-path-of-font-file-from-asset-folder-and-how-to-use-that-path-to-set-s

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