c# - 如何在 StackLayout 中维护 Xamarin Forms 控件的纵横比

标签 c# user-interface layout xamarin.forms

我有一个SkiaSharp view which is embedded in a Xamarin.Forms应用程序。 SkiaSharp View 需要以特定的纵横比绘制。 View 的宽度取决于其父 View (和手机尺寸/习惯用法),因此首次创建 View 时宽度并不总是已知,因此我无法设置 HeightRequest当 View 首次构建时。

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

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

最佳答案

由于 View 的宽度在第一次创建时无法确定,因此代码必须对宽度变化使用react并设置当时的 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 是否必要,但上面的代码对我有用。

关于c# - 如何在 StackLayout 中维护 Xamarin Forms 控件的纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56044457/

相关文章:

android - 带有多个文本的按钮

user-interface - 在 Goland IDE 中运行 GUI 应用程序

android - 将 xml 页面与布局链接起来

css - 为什么 CSS 布局全尺寸和高度不使用绝对定位?

java - 将 JSON 转换为 Java 类(从 Android 应用程序调用 WebApi)

c# - 在动态生成的程序集中捕获错误

python - sublime 文本编辑器使用什么 gui 库?

c# - 我可以重构我的 linq select 吗?

c# - ODBC 连接问题 : Function Sequence error when executing anything

android - 在相对布局中将 textView 定位在另一个 textView 下的问题