【问题标题】:How to use font-face in xamarin UWP如何在 xamarin UWP 中使用字体
【发布时间】:2019-05-27 19:34:39
【问题描述】:

我正在开发跨平台应用程序。在 webview 我想使用@font-face。它在 Android 上运行良好,但在 UWP 上无法运行。我的字体文件位于 Assets/Fonts 文件夹和样式表中,我使用以下代码:

@font-face {
    font-family: 'defont';
    src: url('Assets/Fonts/mher.ttf');
}

在 Android 中我使用的是这个:

src: url('file:///android_asset/mher.ttf');    

但是当我在 UWP 中尝试相同的方法时,它不起作用。 请问有人知道吗?

更新:

下面是我使用普通 WebView 的 C# 代码。我正在从本地 html 文件中获取 html 内容,替换一些占位符并将新的 html 字符串显示到 WebView。

var browser = new WebView();
var htmlSource = new HtmlWebViewSource();

var assembly = IntrospectionExtensions.GetTypeInfo(typeof(WebViewPage)).Assembly;
Stream stream = assembly.GetManifestResourceStream("MyApp.Assets.MyTemplate.html");

string templateHtml = "";
using (var reader = new StreamReader(stream))
{
    templateHtml = reader.ReadToEnd();
}

templateHtml = templateHtml.Replace("{pageHeading}", _post.Title);
templateHtml = templateHtml.Replace("{body}", _post.Content);
if (_post.IsFeaturedImageAvailable)
{
    templateHtml = templateHtml.Replace("{imgSrc}", _post.FeaturedImageUrl);
}else
{
    templateHtml = templateHtml.Replace("{imgSrc}", "");
}
templateHtml = templateHtml.Replace("pdfprnt-buttons", "pdfprnt-buttons hide");

htmlSource.Html = templateHtml;
htmlSource.BaseUrl = DependencyService.Get<IBaseUrl>().Get();
browser.Source = htmlSource;
Content = browser;

【问题讨论】:

  • 这个链接只是告诉你如何设计一个 html 页面。样式表已经工作正常,我的 html 页面正在从样式表中获取样式。唯一的问题是它没有得到@font-face。
  • 此链接用于在 xamarin 表单控件(如标签等)中使用自定义字体。我已经在标签上使用此字体,并且工作正常。问题是在使用 css @fone-face 属性的 html 页面上的 WebView 中使用。
  • 你读到最后了吗?

标签: xamarin uwp


【解决方案1】:

它在 UWP 中有特殊的Uri Scheme。要获取 Assets 文件夹中的字体,您需要使用 ms-appx-web://。请尝试以下代码。

@font-face {
    font-family: 'defont';
    src: url('ms-appx-web:///Assets/Fonts/mher.ttf');
}

更新

我使用了HybridWebView,可以直接加载本地html文件。然后在 UWP 项目中添加 css 文件。

html,body{margin:0;padding:10px}

@font-face {
    font-family: 'MyWebFont';
    src: url('ms-appx-web:///Assets/hello.ttf')
}

body, p, h1, span {
    font-family: 'MyWebFont';
}

这是您可以参考的code sample

【讨论】:

  • 虽然我已经试过了,但现在又试了一次,还是不行。我已经测试了 ms-appx 和 ms-appx-web。两者都不起作用。
  • 看来HybridWebview可以解决问题。我的本地 html 文件中有一个占位符,例如 {myPlaceHolder},在向用户显示之前,我需要用一些动态 html 替换这个占位符。在我以前的方法中,通过在 html 字符串上使用 C# 替换函数很简单。在向用户显示 html 之前如何替换这个占位符?
  • 能否分享一个代码示例,我将快速查看问题?
  • 我已经更新了我的问题帖子。在我的代码中,我在 html 字符串中做了很多替换。但不知道在 HybridWebView 中是否可行。
  • 好的,我会检查的。
猜你喜欢
  • 2017-01-02
  • 2017-02-11
  • 2017-10-13
  • 2019-12-01
  • 2017-02-06
  • 1970-01-01
  • 2017-06-01
  • 1970-01-01
  • 2020-04-21
相关资源
最近更新 更多