我一直致力于优化我的Xamarin.Forms应用,以及我的CarouselPage如何滚动图像。我实现了逻辑,一次只能延迟加载3个图像(转盘中的某个点可能有100个)。
以下是我的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();
}
}
这是填充Carousel的(CustomContent)ContentPages中调用的代码:
public void LoadImage ()
{
this.Content = layout;
}
public void UnloadImage ()
{
this.Content = null;
}
答案 0 :(得分:1)
所以...图像有问题,因为它们不会被自动处理掉。
我的建议是为ImageView提供一个自定义渲染器,用于检测包含ContentPage的内容何时出现并消失,并根据需要加载/处置图像。
答案 1 :(得分:1)
此代码非常适用于几个小问题。有时,快速滑动时不会调用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();
}