Jan
Jan

Reputation: 19

Performance dynamic adding images

I have content page with gallery of images (100 pcs). But loading the page takes a long time (avg = 5-7 sec). I try to dynamically load images to sclollView in alt.Thread. Here my code:

    public ScrollView CreateGallery(List<MetroButton> controls)
    {
        var stack = new StackLayout(){Orientation = StackOrientation.Vertical, Spacing = 0};
        if (controls.Count == 0)
            return new ScrollView ();

        ScrollView scoll = new ScrollView () { Orientation = ScrollOrientation.Vertical};
        scoll.Content = stack;

        //here dynamically add images to scrollView
        Task.Run(() =>     
        {

                for (int i = 0; i < controls.Count - 1; i = i + 2)
                {
                    stack.Children.Add(createDoubleImages(controls[i], controls[i+1]));
                }

                if (controls.Count % 2 != 0) 
                {
                    stack.Children.Add(createDoubleImages(controls[controls.Count - 1], null));
                }
        });

        return scoll;

    }

But it does not help. How can i organize the withdrawal of a large number of images on the page?

Upvotes: 0

Views: 1227

Answers (2)

Daniel Luberda
Daniel Luberda

Reputation: 7454

Some tips:

  • Use ListView - images will be loaded while scrolling dynamically (not everything at once)

  • You could try to replace Image with CachedImage from: https://github.com/molinch/FFImageLoading - it queues image loading/downloading and automatically caches them. It could make performance better - page will be loaded instantly. And images will be loaded from another thread when ready.

One more thing: You're modifying UI from another thread (Task.Run) - you can't do this. Use Device.BeginInvokeOnMainThread inside your task.

Upvotes: 1

eakgul
eakgul

Reputation: 3698

I've faced some issues when implementing a DataGrid component for Xamarin.Forms and it was sufferingly slow. I offer to use ListView for that purpose and make a custom template for showing images inside it.

  • Sample Code:

< ListView ItemsSource="{Binding ImagesList}" RowHeight="120">
 < ListView.ItemTemplate>
   < DataTemplate>
     < ViewCell>
       < ViewCell.View>
         < Image Source="{Binding .}" Aspect="Fill"/ > 
         </ Grid>
       </ ViewCell.View>
     </ ViewCell>
   </ DataTemplate>
 </ ListView.ItemTemplate>
</ ListView>

Upvotes: 0

Related Questions