用框架建造金字塔

时间:2018-12-22 09:30:56

标签: xaml xamarin.forms xamarin.ios xamarin.android

我想在Xamarin.Forms中使用Frame元素构建金字塔。我想使用Grid布局,但是很难,因为下一行的帧会重叠。在这种情况下使用哪种最佳布局? StackLayoutAbsoluteLayout还是其他?

Pyramid like this

1 个答案:

答案 0 :(得分:1)

我将使用AbsoluteLayout处理此问题,并在后面的代码中生成金字塔。这样可以节省很多打字时间,甚至更快。

大概的代码是:

private void BuildPyramid()
{
    int cellSize = 40;
    int height = 8;

    for (int row = 0; row < height - 1; row++) //one less to have two cells on top row
    {
        //add "empty" space equal to a multiple of half-size of a cell
        int startX = row * cellSize / 2; 
        var numberOfColumns = height - row; //each row has one less cell
        for (int column = 0; column < numberOfColumns; column++)
        {
            var x = column * cellSize + startX;
            var y = (height - row - 1) * cellSize; //y-axis decreases going down
            var frame = new Frame()
            {
                WidthRequest = cellSize,
                HeightRequest = cellSize,
                Margin = new Thickness(2), 
                BorderColor = Color.CornflowerBlue
            };
            AbsLayout.Children.Add(frame);
            AbsoluteLayout.SetLayoutBounds(frame, new Rectangle(x, y, cellSize, cellSize));
        }
    }
}

结果:

Result

作为旁注,如果您正在寻找仅XAML的方法-也可以使用Grid方法,但是您必须在这里做一些技巧-您必须添加的单元格数是单元格的两倍在最宽的行中,使用单元格的一半宽度进行布局,并利用Grid.ColumnSpan来使Frames始终一次跨越两列:

<Grid HorizontalOptions="Center" ColumnSpacing="0" RowSpacing="0">
    <Grid.Resources>
        <Style TargetType="Frame">
            <Setter Property="BorderColor" Value="CornflowerBlue" />
            <Setter Property="Margin" Value="2" />
        </Style>
    </Grid.Resources>
    <Grid.RowDefinitions>
        <RowDefinition Height="30" />
        <RowDefinition Height="30" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="15" />
        <ColumnDefinition Width="15" />
        <ColumnDefinition Width="15" />
        <ColumnDefinition Width="15" />
        <ColumnDefinition Width="15" />
        <ColumnDefinition Width="15"  />
    </Grid.ColumnDefinitions>
    <!-- top row -->
    <Frame Grid.Column="1" Grid.ColumnSpan="2" />
    <Frame Grid.Column="3" Grid.ColumnSpan="2" />

    <!-- bottom row -->
    <Frame Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" />
    <Frame Grid.Row="1" Grid.Column="2" Grid.ColumnSpan="2" />
    <Frame Grid.Row="1" Grid.Column="4" Grid.ColumnSpan="2" />
</Grid>

收益:

Sample Grid