【发布时间】:2016-04-25 14:43:12
【问题描述】:
我想用我的应用程序的自定义字体更改我的 fontfamilly。
在 Xamarin 文档中,我可以看到如何仅针对一个标签更改字体家族,但不能针对我的整个应用程序!
我使用适用于 Android 和 IOS 的 Xamarin 表单!
我需要更改我的字体: -列表视图 -纽扣 -标签
谢谢
【问题讨论】:
标签: listview button fonts label xamarin.forms
我想用我的应用程序的自定义字体更改我的 fontfamilly。
在 Xamarin 文档中,我可以看到如何仅针对一个标签更改字体家族,但不能针对我的整个应用程序!
我使用适用于 Android 和 IOS 的 Xamarin 表单!
我需要更改我的字体: -列表视图 -纽扣 -标签
谢谢
【问题讨论】:
标签: listview button fonts label xamarin.forms
您可以使用Global Style 将更改应用于您应用中的所有元素。要更改所有 Label 元素的字体,您可以这样做:
<Application xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Styles.App">
<Application.Resources>
<ResourceDictionary>
<Style TargetType="Label">
<Setter Property="FontFamily" Value="sans-serif" />
<Setter Property="FontSize" Value="12" />
</Style>
</ResourceDictionary>
</Application.Resources>
</Application>
【讨论】:
<OnPlatform x:Key="GothamBook" x:TypeArguments="Font" iOS="GothamHTF-Book" Android="GothamHTF-Book.otf#GothamHTF-Book" />。 [加上适当位置的字体资源] 然后在任何按钮/标签/条目Style,我做<Setter Property="Font" Value="{StaticResource GothamBook}"。
这样您就可以按照您的意图使用 XAML 代码:
<Label FontFamily="Arial" Text="Hi there" />
Android 您可以为您需要的所有视图覆盖默认渲染器。这是标签的示例。您可以对列表视图和按钮执行相同操作。
[assembly: ExportRenderer (typeof (Label), typeof (MyLabelRenderer))]
namespace MyApp.Droid
{
public class MyLabelRenderer : LabelRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
if ( !String.IsNullOrEmpty(Element.FontFamily) )
Control.Typeface = Typeface.CreateFromAsset(Forms.Context.Assets, "Fonts/" + Element.FontFamily + ".otf");
}
}
}
当然,您需要将其映射到嵌入自定义字体的位置。在我的例子中 Assets/Fonts/Arial.otf(构建操作:AndroidAsset)。
在 iOS 中,您需要将它添加到 Resources 文件夹:Resources/Arial.otf(构建操作:BundleResource),它应该可以与上面的 XAML 代码一起使用。
【讨论】:
OnPlatform 正确定义字体,请参阅我对 Jason 的回答(展开以显示更多 cmets)的评论。