Out of memory loading image on Xamarin.Forms

15,272

Maybe this can help you manage the memory:

https://github.com/luberda-molinet/FFImageLoading

Share:
15,272
Bernardo Rocha
Author by

Bernardo Rocha

A lover of Xamarin and Android Studio.

Updated on August 01, 2022

Comments

  • Bernardo Rocha
    Bernardo Rocha almost 2 years

    My app needs to load the same image a certain number of times. Thus, I need to manage the memory usage because after a few iterations it runs out of memory. I am trying to use Garbage Collector, but it isn't working. I am doing this in my Content Page.

    My code looks like:

    private async Task ExecuteTests(string imageResource) 
    {
    
        // Do stuff
    
        for (int q = 0; q < NUMBER_OF_TESTS; q++) {
    
            // Do some work
    
            await LoadImageAsync (imageResource);
    
            // Do stuff
    
            if (q < NUMBER_OF_TESTS - 1) {
                stkImage.Children.Remove(mImageTested);
                mImageTested = null;
                GC.Collect ();
            }
        }
    }
    
    private async Task LoadImageAsync(string imageURI) 
    {
        mImageTested = new Image { Aspect = Aspect.AspectFit };
        Task<ImageSource> result = Task<ImageSource>.Factory.StartNew(() => ImageSource.FromFile(imageURI));
        mImageTested.Source = await result;
        stkImage.Children.Add(mImageTested);
    }