首页 > 解决方案 > 如何在 StackLayout 中维护 Xamarin Forms 控件的纵横比

问题描述

我有一个嵌入在 Xamarin.Forms应用程序中的 SkiaSharp 视图。SkiaSharp 视图需要以特定的纵横比绘制。视图的宽度取决于其父级(和手机大小/习惯用法),因此在首次创建视图时并不总是知道宽度,因此我无法在首次构建视图时设置HeightRequest 。

我不能使用RelativeLayout,因为我需要在StackLayout 中有SkiaSharp 视图,并在视图下放置更多控件。另外,我正在寻找一种更通用的解决方案,我可以将 SkiaSharp 视图放置在任何布局对象(如网格)中。

有没有办法让我为 SkiaSharp 视图指定纵横比,并让它根据所需的纵横比和宽度自动调整其高度?

标签: c#user-interfacelayoutxamarin.forms

解决方案


由于第一次创建时无法确定视图的宽度,因此代码必须对宽度的变化做出反应,并在那时设置 HeightRequest。


// If you want to dynamically adjust the aspect ratio after creation
// this property should have logic in its setter to adjust the height request
public float DesiredAspectRatio { get; set; }

public MyControl()
{
   // Subscribe to the SizeChanged event in the constructor
   SizeChanged += HandleSizeChanged;
}

private void HandleSizeChanged(object sender, EventArgs e)
{
   if (this.Width > 0 && desiredAspectRatio > 0)
   {
       var desiredHeightRequest = this.Width / DesiredAspectRatio;
       // int it to make sure there's no weird recursive behavior
       // caused in release by how floats/doubles are handled.
       if((int)desiredHeightRequest != (int)HeightRequest)
       {
           this.HeightRequest = (int)desiredHeightRequest;
           InvalidateMeasure();
       }
   }
}

我不确定是否InvalidateMeasure有必要,但上面的代码对我有用。


推荐阅读