我对Xamarin和XAML还是陌生的,如果我的问题很愚蠢,请原谅我。
我有一个位于绝对布局内容内部的图像,该图像大于屏幕的宽度和高度(捏和平移作品)。我现在正在尝试创建一个位于图像顶部的网格,并最终使用按钮填充每个单元格(一种获取X,Y位置的粗略方法)。这是很粗糙的,我会承认的,但是我想这样做,如果有的话,我会学习不要做什么。
这是我的XAML,
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyProject.Code"
x:Class="MyProject.Views.myImage"
HeightRequest="771"
WidthRequest="900">
<ContentPage.Content>
<AbsoluteLayout HorizontalOptions="FillAndExpand">
<local:PinchAndPanContainer>
<Image Source="map.png"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"
Aspect="Fill"
Opacity="50"/>
</local:PinchAndPanContainer>
</AbsoluteLayout>
</ContentPage.Content>
</ContentPage>
这是我的.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace MyProject.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class myImage: ContentPage
{
public myImage()
{
InitializeComponent();
// Creates the grid
InitializeGrid(2);
}
void InitializeGrid(int res)
{
Grid grid = new Grid();
var red = new BoxView { Color = Color.Red };
var grn = new BoxView { Color = Color.Green };
var blu = new BoxView { Color = Color.Blue };
var yel = new BoxView { Color = Color.Yellow };
grid.WidthRequest = 900;
grid.HeightRequest = 771;
grid.VerticalOptions = LayoutOptions.FillAndExpand;
grid.HorizontalOptions = LayoutOptions.FillAndExpand;
for (int MyCount = 0; MyCount < res; MyCount++)
{
grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
}
grid.Children.Add(red, 0, 0);
grid.Children.Add(grn, 0, 1);
grid.Children.Add(blu, 1, 0);
grid.Children.Add(yel, 1, 1);
}
}
}
如何获得位于图像顶部的2x2网格?我想在创建网格时采用C#路线,以便创建循环并传入网格的“分辨率”,3x3、100x100等。
执行此操作时,没有任何反应。即使我注释掉几乎所有显示图像的XAML,我仍然一无所获。不知道从这里去哪里。
答案 0 :(得分:0)
为您的AbsoluteLayout
添加一个名称(即x:Name="layout"
),以便您可以通过.Children.Add
将网格作为父对象
我对InitializeGrid方法进行了几次更改,以在AbsoluteLayout中正确设置网格
仅供参考:创建包含大量元素的网格将是一个巨大性能问题。
void InitializeGrid(int res)
{
var grid = new Grid
{
RowSpacing = 0,
ColumnSpacing = 0
};
AbsoluteLayout.SetLayoutBounds(grid, new Rectangle(1, 1, 1, 1));
AbsoluteLayout.SetLayoutFlags(grid, AbsoluteLayoutFlags.All);
for (int MyCount = 0; MyCount < res; MyCount++)
{
grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
}
grid.Children.Add(new BoxView { Color = Color.Red, Opacity=0.5 }, 0, 0);
grid.Children.Add(new BoxView { Color = Color.Green, Opacity = 0.5 }, 0, 1);
grid.Children.Add(new BoxView { Color = Color.Blue, Opacity = 0.5 }, 1, 0);
grid.Children.Add(new BoxView { Color = Color.Yellow, Opacity = 0.5 }, 1, 1);
layout.Children.Add(grid);
}