如何使用Xamarin表单(MAUI)中的dll/nuget从核心项目访问MaterialIconsFont.ttf



我已经创建了两个.Net MAUI项目。一个是核心项目,另一个是子项目。我想为所有常见的功能创建nuget包,如样式、字体和控件等。

为此,我在Core项目中添加了MaterialFontIcons.ttf文件,还创建了一个静态FontIconHelper类来访问ttf文件中可用的所有字体。

我想在我的子项目中使用相同的图标,所以我已经将核心项目的dll文件用于子项目。我能够访问FontIconHelper类,但我不能自己访问ttf文件。

我必须在我的智利项目中添加MaterialFontIcons.ttf文件,而不是在我运行应用程序时只显示图标,否则它会显示"偶像

以下是我所做的:

核心项目步骤:

1从下载的材料设计字体文件https://materialdesignicons.com/

2在参考资料中添加了MaterialFontIcons.ttf-->字体文件夹。

3将其构建动作设置为MauiFont。

4在依赖项注入中注册字体,以便在子项目中使用。

5创建了静态FontIconHelper.cs类来访问ttf图标/字体。

5我已经构建了解决方案,并从它的/bin文件夹中获得了.dll文件

FontIconHelper.cs类

public static class FontIconHelper
{
public const string MaterialDesignIconsFont = "MaterialDesignIconsFont";
public const string VectorSquare = "U000f0001";
public const string AccessPointNetwork = "U000f0002";
public const string AccessPoint = "U000f0003";
public const string Account = "U000f0004";
}

子项目步骤:

1我在这里添加了从Master项目生成的dll文件。2尝试访问Xaml中的FontIcon,如下所示:

Added name space: xmlns:helper="clr-namespace:Mobile.UI.Core.Helpers;assembly=Mobile.UI.Core"
<Image x:Name="image" HeightRequest="20" HorizontalOptions="EndAndExpand">
<Image.Source>
<FontImageSource
Glyph="{x:Static helper:FontIconHelper.AccessPoint}"
Size="20"
Color="Black"
FontFamily="{x:Static helper:FontIconHelper.MaterialDesignIconsFont}"/>
</Image.Source>
</Image>

3当运行该应用程序时,它显示为"而不是实际的图标。

4然后我在智利项目中添加了ttf文件,并将其构建操作设置为MauiFont,并在MauiProgram.cs中注册了字体,如下所示:

var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.ConfigureFonts(fonts =>
{
fonts.AddFont("MaterialdesignIcons-Font.ttf", "MaterialdesignIconsFont");
})
.ConfigureServices();

之后,它会在应用程序中显示图标属性。

有人知道如何直接从核心项目到子项目访问Fonts.ttf文件而不将其添加到子项目吗?

您需要将ttf分配为csproj中的嵌入式资源,以便在类库之间传递。或者,您可以使用已经完成此工作的图标库。

这里有一个基于材质图标的一些图标库。https://www.nuget.org/packages/AathifMahir.Maui.MauiIcons.Material

此外,您还可以在此处查找其他变体。https://www.nuget.org/profiles/Aathif_Mahir

首先,您必须在Core项目的某个位置创建自己的MauiAppBuilder。可以是这样的类:

public static class AppBuilderExtensions
{    
public static MauiAppBuilder UseRamdomFunctionNameXYZASDF( this MauiAppBuilder builder )
{      
builder = FontsMauiAppBuilderExtensions.ConfigureFonts(builder, (Action<IFontCollection>)(fonts =>
{
fonts.AddFont("MaterialdesignIcons-Font.ttf", "MaterialdesignIconsFont");
}));
return builder;
}   
}

然后在您的MauiProgram.cs集合中:

var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.UseRamdomFunctionNameXYZASDF()//this is it, also you can use for add styles and similar
.ConfigureFonts(fonts =>
{
//here you inserted here the Material fonts before... no needed anymore
})
.ConfigureServices();

我测试了这个并为我工作…字体(.ttf(也可以在Core项目的任何文件夹中并工作。希望能帮助你

尝试添加一个新文件"AssemblyInfo.cs";到核心项目根文件夹,带有:

[assembly: XamlCompilation(XamlCompilationOptions.Compile)] 
[assembly: ExportFont("MaterialdesignIcons-Font.ttf", Alias = "MaterialdesignIconsFont")]

最新更新