首页 > 解决方案 > Xamarin Forms 将不同字体大小的标签垂直对齐到同一基线

问题描述

我在水平方向的堆栈布局中有两个并排的标签。标签有不同的字体大小。无论字体大小如何,我都想让每​​个标签文本的基线(底部边缘)相同。但是,xamarin 表单的默认行为不是这样做的。以下代码

    <StackLayout Orientation="Horizontal" >
            <Label  FontSize="12" Text="A Noble Spirit"></Label>
            <Label  FontSize="18" Text="Embiggens The Smallest Man"></Label>
    </StackLayout>

在 android 上运行以下视图的结果。

图 1,不同字体大小标签的不同基线

我尝试了许多不同的组合来设置垂直文本对齐和标签上的垂直选项属性。我能想到的最好的(以及我认为应该起作用的)是添加垂直选项=结束它们。这稍微改善了一些情况,但仍然存在不匹配,因此较大标签的文本(embiggens)开始高于较小标签 - 如下所示:

    <StackLayout Orientation="Horizontal" >
            <Label VerticalOptions="End" FontSize="12" Text="A Noble Spirit"></Label>
            <Label VerticalOptions="End" FontSize="18" Text="Embiggens The Smallest Man"></Label>
    </StackLayout>

图,好但不是很好

如您所见,有些改进,但仍未对齐。这让我有点上墙了。我开始认为这可能是 Xamarin Forms for android 中的一个错误。(稍后当我可以在 iOS 上运行一个示例以查看它是否特定于 android 时,我将添加到这个问题。)。

我可以通过将顶部边距添加到等于字体大小差异的较小标签来破解它,这很严重,我不想在我的系统中引入技术债务和维护。但这里是为了展示它。希望不必求助于这个...

    <StackLayout Orientation="Horizontal" >
            <Label FontSize="12" Margin="0,6,0,0" Text="A Noble Spirit"></Label>
            <Label FontSize="18" Text="Embiggens The Smallest Man"></Label>
    </StackLayout>

图 3,Hacky Sack

标签: xamarinxamarin.formsxamarin.androidvertical-alignment

解决方案


原因:如果你设置了两个标签的背景颜色,你可以看到,因为标签有一个默认的“填充”。该值取决于它的高度。

在此处输入图像描述

解决方案:

您可以将两个不同的字符串放在同一个标​​签中。它有一个名为FormattedText的属性,它允许您为 Label 设置格式化文本。

<StackLayout Orientation="Horizontal"  VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand">
        <Label FormattedText="{Binding FormattedTextContent}" x:Name="label" ></Label>
        <Label FormattedText="{Binding FormattedTextContent}" x:Name="label2" ></Label>
</StackLayout>

在后面的代码中

FormattedTextContent = new FormattedString();
var fs = new FormattedString();
fs.Spans.Add(new Span { Text = "A Noble Spirit " , FontSize = 12, TextColor = Color.Black });
fs.Spans.Add(new Span { Text = "  ", FontSize = 18 });
label.FormattedText = fs;

var fs1 = new FormattedString();

fs.Spans.Add(new Span { Text = "  ", FontSize = 12 });
fs.Spans.Add(new Span { Text = "Embiggens The Smallest Man", TextColor = Color.Black, FontSize = 18 });
label2.FormattedText = fs1;

当然你可以使用 MVVM 因为它是一个可绑定的属性。

在此处输入图像描述


推荐阅读