我一直在优化我的Xamarin.Forms应用程序,以及我的CarouselPage如何滚动图像。我已经实现了一次只延迟加载3个图像的逻辑(转盘中的某个点可能有100个)。
- currentIndex是滑动前页面的索引
- WINDOW_SIZE是一个常数,用于向左加载多少图像当前页面的右侧
- CustomContent是填充转盘的ContentPage类
- 布局是CustomContent内部的私有RelativeLayout在构造函数中生成的ContentPage
以下是在我的Carousel的OnCurrentPageChanged()事件上调用的代码:
protected override void OnCurrentPageChanged ()
{
base.OnCurrentPageChanged();
int newIndex = this.Children.IndexOf(this.CurrentPage);
if (newIndex > currentIndex)
{
currentIndex++;
UnloadImages();
LoadImages();
}
else if (newIndex < currentIndex)
{
currentIndex--;
UnloadImages();
LoadImages();
}
}
以下是正在调用的函数:
private void LoadImages ()
{
int lowIndex = currentIndex - WINDOW_SIZE >= 0 ? currentIndex - WINDOW_SIZE : 0;
int highIndex = currentIndex + WINDOW_SIZE <= this.Children.Count() - 1 ? currentIndex + WINDOW_SIZE : this.Children.Count() - 1;
for (int i = lowIndex; i <= highIndex; i++)
{
CustomContent custom = (CustomContent) this.Children[i];
custom.LoadImage();
}
}
private void UnloadImages ()
{
int lowIndex = currentIndex - WINDOW_SIZE >= 0 ? currentIndex - WINDOW_SIZE : 0;
int highIndex = currentIndex + WINDOW_SIZE <= this.Children.Count () - 1 ? currentIndex + WINDOW_SIZE : this.Children.Count () - 1;
if (lowIndex - 1 >= 0)
{
CustomContent custom = (CustomContent) this.Children[lowIndex - 1];
custom.UnloadImage();
}
if (highIndex + 1 <= thoughts.Count () - 1)
{
CustomContent thought = (CustomContent) this.Children[highIndex + 1];
custom.UnloadImage();
}
}
这是在填充旋转木马的(CustomContent)ContentPages中调用的代码:
public void LoadImage ()
{
this.Content = layout;
}
public void UnloadImage ()
{
this.Content = null;
}
所以。。。图像是有问题的,因为它们不是自动处理的。
我的建议是为ImageView提供一个自定义渲染器,它可以检测包含ContentPage的内容何时出现和消失,并酌情加载/处理图像。
此代码运行良好,很少出现小问题。有时,OnCurrentPageChanged在快速滑动时不会被调用,currentIndex也会不同步。为了纠正这一点,我更改了currentIndex:
protected override void OnCurrentPageChanged () {
base.OnCurrentPageChanged();
int newIndex = this.Children.IndexOf(this.CurrentPage);
//Set currentIndex, no need to use increment,decrement
currentIndex = newIndex;
UnloadImages();
LoadImages();
}