Xamarin.Forms中如何消除文字与线段间空白,实现文字紧贴线段显示
问题原因
空白来自两个层面:
- StackLayout默认自带子元素间距,默认值为6,这是间隙产生的主要原因
- 不同平台下Label、Line控件本身可能存在微小的默认内置边距
解决方案1:修改现有StackLayout配置
直接给StackLayout添加Spacing="0"属性消除默认间距,再通过微调Line的Margin即可实现贴合效果,修改后代码如下:
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="alphatrial.MainPage" BackgroundColor="#ffc40c"> <StackLayout Spacing="0"> <Label Text="ISC - Alpha" TextColor="Black" FontSize="Large" FontAttributes="Bold" FontFamily="MyAwesomeCustomFont" HorizontalOptions="End" Margin="0,50,20,0" /> <Line Stroke="black" X1="0" X2="340" StrokeThickness="2" Margin="0,0,0,-3" /> <Label Text="App" TextColor="White" FontSize="Large" FontAttributes="Bold" FontFamily="MyAwesomeCustomFont" HorizontalOptions="End" Margin="0,0,20,0"/> </StackLayout> </ContentPage>
可以根据实际显示效果调整Line的Bottom Margin数值(上述代码中是-3),直到贴合效果符合预期即可。
解决方案2:改用Grid实现更精准的布局
如果需要更高的布局可控度,可以替换StackLayout为Grid,完全不受默认间距影响:
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="alphatrial.MainPage" BackgroundColor="#ffc40c"> <Grid Margin="0,50,0,0" RowSpacing="0"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Label Grid.Row="0" Text="ISC - Alpha" TextColor="Black" FontSize="Large" FontAttributes="Bold" FontFamily="MyAwesomeCustomFont" HorizontalOptions="End" Margin="0,0,20,0" /> <Line Grid.Row="1" Stroke="black" X1="0" X2="340" StrokeThickness="2" /> <Label Grid.Row="2" Text="App" TextColor="White" FontSize="Large" FontAttributes="Bold" FontFamily="MyAwesomeCustomFont" HorizontalOptions="End" Margin="0,0,20,0"/> </Grid> </ContentPage>
内容的提问来源于stack exchange,提问作者rana hd
相关产品推荐
相关产品推荐

