Xamarin Form 4.3中Label使用sans-serif字体的技术咨询
Hey there! Let's get that sans-serif font working properly across your Android and iOS apps. The key here is that Android and iOS use different system font names for their default sans-serif styles, so a one-size-fits-all FontFamily="sans-serif" won't work for both platforms. Here's how to fix it:
Using System Default Sans-Serif Fonts
If you just want to use each platform's native default sans-serif font (no external fonts needed), use the OnPlatform tag to target each OS separately:
<Label Grid.Row="1" Text="TestFontFamily" LineBreakMode="WordWrap" FontSize="20" HorizontalOptions="Center" VerticalOptions="End" TextColor="White"> <Label.FontFamily> <OnPlatform x:TypeArguments="x:String"> <!-- Android natively recognizes "sans-serif" as its system default sans-serif --> <On Platform="Android" Value="sans-serif" /> <!-- iOS uses San Francisco; ".SF UI Text" is the default body text variant --> <On Platform="iOS" Value=".SF UI Text" /> </OnPlatform> </Label.FontFamily> </Label>
Quick Notes for iOS:
- If you need a sans-serif font for headings instead of body text, use
.SF UI Displayinstead of.SF UI Text. - These are system fonts, so you don't need to package any extra files with your app.
Using Custom Sans-Serif Fonts from Google Fonts
If you want to use a specific sans-serif font (like Roboto, Open Sans, etc.), you'll need to embed the font files into your project:
- Download the font files (
.ttfor.otf). - Add the files to your project:
- For Android: Set the Build Action to
AndroidAsset - For iOS: Set the Build Action to
BundleResource
- For Android: Set the Build Action to
- Update your Label's
FontFamilyto match the font's internal name (this might differ from the file name—use a font viewer tool to check the official name). For example, if using Open Sans Regular:
Or use<Label FontFamily="OpenSans-Regular" ... />OnPlatformif the font name varies by platform (rare, but possible).
That should cover both scenarios! Let me know if you run into any snags with font embedding or naming.
内容的提问来源于stack exchange,提问作者Jefferson

