c# - 如何在 StackLayout 中维护 Xamarin Forms 控件的纵横比
问题描述
我有一个嵌入在 Xamarin.Forms应用程序中的 SkiaSharp 视图。SkiaSharp 视图需要以特定的纵横比绘制。视图的宽度取决于其父级(和手机大小/习惯用法),因此在首次创建视图时并不总是知道宽度,因此我无法在首次构建视图时设置HeightRequest 。
我不能使用RelativeLayout,因为我需要在StackLayout 中有SkiaSharp 视图,并在视图下放置更多控件。另外,我正在寻找一种更通用的解决方案,我可以将 SkiaSharp 视图放置在任何布局对象(如网格)中。
有没有办法让我为 SkiaSharp 视图指定纵横比,并让它根据所需的纵横比和宽度自动调整其高度?
解决方案
由于第一次创建时无法确定视图的宽度,因此代码必须对宽度的变化做出反应,并在那时设置 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++ - 在类中设置 Arduino 字符串值
- string - 传递参数时批量使用“=”作为字符串
- php - php - 无法使用 PDO 连接到数据库
- python - int 对象在输入第一个输入的数量后不可迭代
- c++ - 使用 pthreds 在 C++ 中进行线程通信
- php - Htaccess 允许给定引用者的文件访问不起作用
- python - 为什么 Django 不迁移我更改的模型?
- javascript - 使用 stringify 和 replace 将 JSON 对象字符串化,其属性名称为大写
- cmake - Cmake 和 vcpkg - 找到正确的库名称
- django - 如何只允许从特定页面访问 url