juliushuck
juliushuck

Reputation: 1684

Xamarin: Load images asyn in view

I m developing a wallpaper app. Therefore I am using Xamarin.Forms. There is a scroll view with all available wallpapers and on top of it, the user can see the selected one bigger.

The problem is that when I start the App I can see that it is a bit lagging. (Images are loading in view) And I don t like that. It looks not good. So I started a new Task in that I am getting the images from the embedded resources. But that doesn't t coast so much time. The time-consuming thing is to display the images in the view. And I can not do that in the task because it has to be an STA thread to access the view.

I want it like this:

The app starts You see a running activity indicator The images are loaded from the resource without blocking the UI thread Images are loaded into view without blocking the UI thread Activity indicator disappears and main grid comes in front

So here is my code:

Check this pastebin for code.

Thank you.

Ok I didn't t fixed the problem but I have a solution:

Task.Factory.StartNew(() =>
        {
            return InitializeImages();
        }).ContinueWith(r =>
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                if (r.Result == GlobalSettings.ImageCount)
                    ButtonsGrid.ColumnDefinitions[1].Width = 0;
                else
                    ButtonsGrid.ColumnDefinitions[1].Width = GridLength.Star;

                for (int i = 0; i < r.Result; i++)
                {
                    ImagesGrid.Children.Add(_previewImages[i]);
                    ImagesStackLayout.Children.Add(_images[i]);
                }
            });

            Thread.Sleep(2000);

            Device.BeginInvokeOnMainThread(async () =>
            {
                await ShowWallpaperInPreview();

                await Loading(false);
            });
        });

I let it lagging in the background. and after a short time, I change from loading to normal view. This way it is lagging in the background (who cares=)

Upvotes: 1

Views: 571

Answers (1)

EvZ
EvZ

Reputation: 12179

A very good candidate to keep your app responsive and cover cases that are not mentioned in your question is an open source project named FFImageLoading.

Here is the list of supported features:

  • Configurable disk and memory caching
  • Multiple image views using the same image source (url, path, resource) will use only one bitmap which is cached in memory (less memory usage)
  • Error and loading placeholders support
  • Images can be automatically downsampled to specified size (less memory usage)
  • Can retry image downloads (RetryCount, RetryDelay)

and much more!

Check the Advanced Usage doc and Wiki for more details.

Upvotes: 1

Related Questions