簡體   English   中英

在Xamarin Forms中更改我的應用程序的字體(所有標簽/列表視圖…)

[英]Change font of my application in Xamarin Forms (all label/listview…)

我想用我的應用程序的自定義字體來更改我的字體。

在Xamarin文檔中,我可以看到如何僅為一個標簽更改字體家族,而不能為整個應用程序更改字體!

我使用適用於Android和IOS的Xamarin Forms!

我需要更改字體:-Listviews -Buttons -Label

謝謝

您可以使用全局樣式將更改應用於應用程序中的所有元素。 要更改所有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>

這樣,您可以像預期的那樣使用XAML代碼:

<Label FontFamily="Arial" Text="Hi there" />

Android您可以覆蓋所需的所有視圖的默認渲染器。 這是Label的示例。 您可以對listview和button進行相同的操作。

[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代碼一起使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM