编辑:
我建议您获取屏幕尺寸并根据屏幕尺寸计算百分比,使用变量值而不是比例值。这样,您可以使用除AbsoluteLayout之外的其他布局,但我在我的示例中使用了AbsoluteLayout:
protected override void OnAppearing()
{
var imageWidth = this.Width;
var imageHeight = this.Height * 0.25;
AbsoluteLayout.SetLayoutBounds(image, new Rectangle(0, 0, imageWidth, imageHeight));
AbsoluteLayout.SetLayoutFlags(image, AbsoluteLayoutFlags.None);
}
在我的测试中,当我使用AbsoluteLayout的比例方法时:
AbsoluteLayout.LayoutBounds = "0,0,1,0.25"
AbsoluteLayout.LayoutFlags="All"
如果页面使用或不使用
Tabbedpage
,两个图像大小的结果会略有不同。
因此,我建议使用代码获取基于[屏幕高度*百分比]的图像大小。
<?xml version="1.0" encoding="utf-8"?>
<TabbedPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:AbsoluteLayoutExample" x:Class="AbsoluteLayoutExample.AbsoluteLayoutExamplePage">
<ContentPage x:Name="MyPage" Title = "Page 1">
<AbsoluteLayout>
<Image x:Name="image" Source="icon.png" Aspect="AspectFill" />
</AbsoluteLayout>
</ContentPage>
<ContentPage Title = "Page 2">
<Label Text="Hello" />
</ContentPage>
</TabbedPage>
代码后端:
protected override void OnAppearing()
{
var imageWidth = this.Width;
var imageHeight = this.Height * 0.25;
AbsoluteLayout.SetLayoutBounds(image, new Rectangle(0,0,imageWidth,imageHeight));
AbsoluteLayout.SetLayoutFlags(image,AbsoluteLayoutFlags.None);
}
内容页面:
XAML:
<?xml version="1.0" encoding="utf-8"?>
<ContentPage Padding="0,20,0,0"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:ContentPageWidthAndHieght"
x:Class="ContentPageWidthAndHieght.ContentPageWidthAndHieghtPage">
<AbsoluteLayout>
<Image x:Name="image" Source="icon.png" Aspect="AspectFill"/>
</AbsoluteLayout>
</ContentPage>
代码后台:
protected override void OnAppearing()
{
var imageWidth = this.Width;
var imageHeight = this.Height * 0.25;
AbsoluteLayout.SetLayoutBounds(image, new Rectangle(0, 0, imageWidth, imageHeight));
AbsoluteLayout.SetLayoutFlags(image, AbsoluteLayoutFlags.None);
}
![enter image description here](https://istack.dev59.com/VGozp.webp)