我有一个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/