我有两个 Label 实例,每个实例都有不同的 FontSize。因此,它们的基线和边界框底部(包括下降空间)之间的距离是不同的。是否可以根据两个标签实例的基线对齐它们?
以下 XAML 和图像显示了我遇到的问题。我尝试通过对
End
和 VerticalOptions
使用 VerticalTextAlignment
对齐来对齐字体。请注意,我添加了颜色来帮助可视化每个项目的大小。
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="LiveTulaMobile.Pages.TestPage"
Title="TestPage">
<HorizontalStackLayout Background="Yellow">
<Label FontSize="48" Text="1,000" VerticalOptions="End" VerticalTextAlignment="End" Background="Red"/>
<Label FontSize="24" Text="kg" VerticalOptions="End" VerticalTextAlignment="End" Background="Pink"/>
</HorizontalStackLayout>
</ContentPage>
此 XAML 产生以下结果:
为了清楚起见,我还放大了图像并添加了我自己的虚线以帮助可视化基线偏移:
这感觉在任何 UI 中都相当常见,但我在网上找不到任何有关如何解决此问题的信息。
请注意,可以向较小的标签添加边距以对齐基线,但我担心,当移动到其他操作系统(iOS)或用户已将字体缩放设置为操作系统级别。
您可以查看有关对齐和定位.NET MAUI控件的文档。您可以为标签添加
Padding="0,0,0,10"
,如下面的代码所示。
<HorizontalStackLayout Background="Yellow">
<Label FontSize="48" Text="1,000" VerticalOptions="End" VerticalTextAlignment="End" Background="Red"/>
<Label FontSize="24" Text="kg" VerticalOptions="End" VerticalTextAlignment="End" Background="Pink" Padding="0,0,0,10" />
</HorizontalStackLayout>
更新:
您可以检查此代码,它运行良好。不需要设置标签的padding。
<StackLayout Background="Yellow">
<HorizontalStackLayout VerticalOptions="Start">
<Label FontSize="48" Text="1,000" VerticalTextAlignment="End" Background="Pink" VerticalOptions="Center"/>
<Label FontSize="24" Text="kg" VerticalTextAlignment="End" Background="Pink" VerticalOptions="Center"/>
</HorizontalStackLayout>
</StackLayout>