问题
I am working on cross platform app. In webview I want to use @font-face. It is working fine on Android but not working on UWP. My font file is in Assets/Fonts folder and in style sheet I am using the below code:
@font-face {
font-family: 'defont';
src: url('Assets/Fonts/mher.ttf');
}
In Android I was using this:
src: url('file:///android_asset/mher.ttf');
But when same approach I try in UWP, it is not working. Please anyone has any idea?
UPDATE:
Below is my C# code of using normal WebView. I am getting html content from local html file, replace some placeholders and display new html string to 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;
回答1:
It has special Uri Scheme within UWP. For for getting the font in the Assets folder, you need use ms-appx-web://. Please try the following code.
@font-face {
font-family: 'defont';
src: url('ms-appx-web:///Assets/Fonts/mher.ttf');
}
Update
I used HybridWebView that could load local html file directly. Then add the css file in UWP project.
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';
}
This is code sample that you could refer.
来源:https://stackoverflow.com/questions/53984563/how-to-use-font-face-in-xamarin-uwp