如何从资产文件夹中获取字体文件的路径,以及如何在Xamarin Android中使用该路径设置SKTypeface? [英] How to get path of font file from asset folder and how to use that path to set SKTypeface in xamarin android?

查看:518
本文介绍了如何从资产文件夹中获取字体文件的路径,以及如何在Xamarin Android中使用该路径设置SKTypeface?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在本地xamarin andorid工作.我面临设置自定义字体的问题.我正在使用"SkiaSharp"插件生成画布视图.该插件位于PCL内部,因此可以在android和ios中使用.

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.

我的资产"文件夹中有一个.ttf文件.

我使用以下代码生成字体路径.

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");

我发送到PCL的此路径以设置"SKTypeface"

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");

我总是将空的SKTypeface作为返回值.

我认为找不到字体路径.

bool flag=File.Exist(FontPath)

它总是返回空值.

如何在xamarin andorid中获取Asset文件夹的路径? 如何将自定义字体设置为SKTypeface?

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

推荐答案

您通常不使用android资产的路径,因为它们位于应用包中.相反,您将获得一个流并进行加载-但是资产流是不可搜索的,因此必须首先复制它们:

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;

我还想说明一下这相对慢",所以您可能要这样做一次,然后重新使用字体.避免直接在paint方法中加载文件,因为绘画发生在UI线程上并且会阻塞.

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.

加载资产时,请勿假设包含根目录"Assets".

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

编辑

在新的v1.59.2版本中,无论流如何,现有的FromStream方法都将按预期工作.

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

这篇关于如何从资产文件夹中获取字体文件的路径,以及如何在Xamarin Android中使用该路径设置SKTypeface?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆