Preloading Images with FFImageLoading

Kramer_Kramer_ USMember ✭✭

Background: I have a custom ContentPage I'm reusing and occasionally loading images into. A CachedImage gets loaded into a StackLayout that is centered within an AbsoluteLayout. Since I'm setting the CachedImage.Source in the code, the image height wasn't adjusting the size of the StackLayout and it wouldn't center vertically. After doing some extensive testing I've got FFImageLoading preloading images, adding the CachedImage and forcing the layout so it shows up centered!

I'm so happy it works I wanted to share my code!

XAML (partial)

<AbsoluteLayout x:Name="absoluteLayout" HorizontalOptions="Fill" VerticalOptions="Fill">
    <StackLayout x:Name="mainLayout" Margin="15" Spacing="20" VerticalOptions="Center" 
        AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0,0,1,1">
        <!-- Elements go here -->


public AlertPage()

    var imageFile = "dynamic_image"; // I get this dynamically
    if (imageFile != null)
        // Preload image so it's width/height can adjust layout
        TaskParameter imageTask;
        // iOS requires the extension, Android loads from CompiledResource
        if (Device.RuntimePlatform == Device.iOS)
            imageFile = string.Format("{0}.png", imageFile);
            imageTask = ImageService.Instance.LoadFile(imageFile);
            imageTask = ImageService.Instance.LoadCompiledResource(imageFile);

        imageTask.Error((Exception obj) => 
            Debug.WriteLine("LoadFile Error: {0}", obj);
        imageTask.Success((ImageInformation info, LoadingResult result) => 
            Debug.WriteLine("LoadFile Success: {0} : {1}", info, result);

            Device.BeginInvokeOnMainThread(() =>
                var image = new CachedImage
                    Source = imageFile
                mainLayout.Children.Insert(0, image);

    ... // Rest of page creation

Sign In or Register to comment.