我使用以下代码来创建和渲染一个简单的标签。布局设置为与屏幕具有相同的高度和宽度。
maincontent = new Microsoft.Maui.Controls.AbsoluteLayout
{
BackgroundColor = Microsoft.Maui.Graphics.Color.FromArgb("#FF221E1F"),
HeightRequest = mainmescreenheight,
IsEnabled = true,
IsVisible = true,
WidthRequest = mainmescreenwidth
};
Microsoft.Maui.Controls.Label newLabel = new Microsoft.Maui.Controls.Label
{
BackgroundColor = Microsoft.Maui.Graphics.Color.FromArgb("#FF221E1F"),
FontAttributes = Microsoft.Maui.Controls.FontAttributes.Bold,
FontFamily = "VerdanaBold",
FontSize = 14,
HorizontalOptions = Microsoft.Maui.Controls.LayoutOptions.Center,
HorizontalTextAlignment = Microsoft.Maui.TextAlignment.Center,
IsEnabled = true,
IsVisible = true,
MinimumHeightRequest = 300,
MinimumWidthRequest = 640,
Text = "Center of Label",
TextColor = Microsoft.Maui.Graphics.Color.FromArgb("#FFFFFFFF"),
VerticalTextAlignment = Microsoft.Maui.TextAlignment.Center,
VerticalOptions = Microsoft.Maui.Controls.LayoutOptions.Center
};
AbsoluteLayout.SetLayoutFlags(newLabel, Microsoft.Maui.Layouts.AbsoluteLayoutFlags.None);
AbsoluteLayout.SetLayoutBounds(newLabel, new Rect(0, 0, 640, 300));
maincontent.Children.Add(newLabel);
我希望文本(在本例中为“标签中心”)垂直和水平居中显示。
虽然文本始终水平居中,但它始终显示在标签的最顶部,就好像 VerticalTextAlignment 和 VerticalOptions 设置为 .Start 而不是 .Center。
如何让文本垂直居中?这是net7.0-windows10.0.19041.0.
假设
我使用以下代码来创建和渲染一个简单的标签。布局设置为与屏幕具有相同的高度和宽度。
您的
AbsoluteLayout
设置是问题所在,最小高度/宽度是不必要的。
您的代码应如下所示:
maincontent = new Microsoft.Maui.Controls.AbsoluteLayout
{
BackgroundColor = Microsoft.Maui.Graphics.Color.FromArgb("#FF221E1F"),
HeightRequest = mainmescreenheight,
WidthRequest = mainmescreenwidth
};
Microsoft.Maui.Controls.Label newLabel = new Microsoft.Maui.Controls.Label
{
BackgroundColor = Microsoft.Maui.Graphics.Color.FromArgb("#FF221E1F"),
FontAttributes = Microsoft.Maui.Controls.FontAttributes.Bold,
FontFamily = "VerdanaBold",
FontSize = 14,
HorizontalOptions = Microsoft.Maui.Controls.LayoutOptions.Center,
HorizontalTextAlignment = Microsoft.Maui.TextAlignment.Center,
Text = "Center of Label",
TextColor = Microsoft.Maui.Graphics.Color.FromArgb("#FFFFFFFF"),
VerticalTextAlignment = Microsoft.Maui.TextAlignment.Center,
VerticalOptions = Microsoft.Maui.Controls.LayoutOptions.Center
};
AbsoluteLayout.SetLayoutFlags(newLabel, Microsoft.Maui.Layouts.AbsoluteLayoutFlags.All);
AbsoluteLayout.SetLayoutBounds(newLabel, new Rect(0, 0, 1, 1));
maincontent.Children.Add(newLabel);
另外,我不知道你为什么会这样
高度请求=主屏幕高度
或
宽度请求=主屏幕宽度
在你的 AbsoluteLayout 中。
AbsoluteLayout 默认适合其父级。