【问题标题】:Build a pyramid with Frames用框架构建金字塔
【发布时间】:2019-05-22 12:00:14
【问题描述】:

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

【问题讨论】:

  • 将每一行构建为一个单独的网格

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


【解决方案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));
        }
    }
}

结果:

附带说明,如果您正在寻找仅 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>

产量:

【讨论】:

  • 非常感谢。这似乎正是我所需要的。我迫不及待想尝试一下。
  • 告诉我进展如何 :-)
  • 我选择 Absolutlayout 方法。我现在已经对其进行了测试,它就像一个魅力。谢谢你的时间:)
  • 编码快乐,节日快乐???!
猜你喜欢
  • 1970-01-01
  • 2021-12-15
  • 2015-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
相关资源
最近更新 更多