EzDev.org

FFImageLoading

FFImageLoading - Image loading, caching & transforming library for Xamarin and Windows


How to preload images using FFImageLoading for all list items in derived Xamarin BaseAdapter class

The FFImageLoading Xamarin Android/iOS image loading library is working fantastic in a custom list by using the following in the BaseAdapter derived class' overriden GetView:

ImageViewAsync imageViewAsync = view.FindViewById<ImageViewAsync>(Resource.Id.Image);
ImageService.LoadUrl(item.ImagePoster).Into(imageViewAsync);

The problem is that when scrolling down the Android ListView it takes too long to download each image and so I'd like to preload some or all the images in the list to make for a better user experience.

So can I preload images with FFImageLoading without loading into an ImageViewAsync?


Source: (StackOverflow)

Android Debugging Failing With "Couldn't connect to logcat, GetProcessId returned: 0" FFImageLoading.Platform.dll.so Not Found

I am having issue debugging Android project. I can deploy to device and run it, all works fine but if I try to debug, the app gets deployed to the device and very briefly opened, splash screen shows up but the app then closes.

I am using Xamarin Forms on Visual Studio 2015.

Device is running Android Oreo (8.0.0). Another device running Android 6.0.1 is debugging fine.

The output shows following:

InspectorDebugSession(11): StateChange: Start -> EntryPointBreakpointRegistered
InspectorDebugSession(11): Constructed
Android application is debugging.
InspectorDebugSession(11): HandleTargetEvent: TargetExited
InspectorDebugSession(11): Disposed
Couldn't connect to logcat, GetProcessId returned: 0

I checked Logcat and it seem to be having issues finding FFImageLoading library:

Time    Device Name Type    PID Tag Message
09-18 14:35:52.361  Huawei Nexus 6P Debug   1560    Mono    AOT: 
image '/usr/local/lib/mono/aot-cache/arm/FFImageLoading.Platform.dll.so' 
not found: dlopen failed: library "/data/app/myapp.android.dev-
WEb1bz8edgF7vwx6uCoZ-A==/lib/arm/libaot-FFImageLoading.Platform.dll.so" not found

I have added Nuget package for FFImageLoading to my projects and Droid project references show it as in image below:

enter image description here


Source: (StackOverflow)

ContentPage containing list view display very slow on Android

I am not sure whether this is my problem or a problem with Xamarin. On an iPad my application can load the page which contain a list of data in ListView. The View Cell inside the ListView can be slightly complex. It contains a profile image, some smaller icons using, which are using FFImageLoading.

On iPad, when I tap a cell of the first page to go into the next page, which contains a list of data, it loads very smoothly. On Android, when I tap on a cell to go into the next page, the detection of the tap is slow and the loading time of the ListView also very slow.

Is there anyway enhance the performance? I thought it was the data I loaded from SQLite. However, after I comment out the ItemsSource on ListView, the loading time is fine.

This is the datatemplate I've used for displaying the cell.

<ViewCell>
               <ViewCell.View>
                    <StackLayout Spacing="0" Padding="0" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
                        <StackLayout Orientation="Horizontal" Spacing="10" Padding="0" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
                            <StackLayout Orientation="Horizontal" HorizontalOptions="StartAndExpand">
                                <controls:CircleImage 
                                    Style="{StaticResource profileImageStyle}"
                                    Margin="10, 10, 10, 10"
                                    Source="{Binding Source}"
                                    BorderColor="White"
                                    BorderThickness="2"
                                    VerticalOptions="Center"
                                    HorizontalOptions="Center">

                                    <controls:CircleImage.GestureRecognizers>
                                        <TapGestureRecognizer  Tapped="OnChildDetailTapped" />
                                    </controls:CircleImage.GestureRecognizers>
                                </controls:CircleImage>

                                <StackLayout VerticalOptions="Fill" Spacing="1" Padding="0,20,0,10" HorizontalOptions="StartAndExpand">
                                    <StackLayout.GestureRecognizers>
                                        <TapGestureRecognizer  Tapped="OnChildDetailTapped" /> 
                                    </StackLayout.GestureRecognizers>
                                    <StackLayout
                                        Orientation="Vertical"
                                        VerticalOptions="Center"
                                        HorizontalOptions="StartAndExpand"> 
                                        <Label x:Name="childName" Text="{Binding DisplayName}" Style="{StaticResource normalFont}"> </Label>
                                        <local:ChildInfoIconsView 
                                            Child="{Binding .}"
                                            VerticalOptions="Fill">
                                        </local:ChildInfoIconsView>


                                        <Label 
                                            x:Name="childNotes"
                                            Style="{StaticResource footnoteFont}"
                                            Text="{Binding ChildNotes, StringFormat={x:Static local:AppResources.formatNotes}}" 
                                            IsVisible="{Binding HasChildNotes}">
                                        </Label>
                                        <Label 
                                            x:Name="noPickupReason" 
                                            Style="{StaticResource footnoteFont}"
                                            Text="{Binding NoPickupReason, StringFormat={x:Static local:AppResources.formatNoPickupReason}}" 
                                            IsVisible="{Binding HasNoPickupReason}">
                                        </Label>
                                        <Label 
                                            x:Name="absentReason" 
                                            Style="{StaticResource footnoteFont}"
                                            Text="{Binding AbsentReason, StringFormat={x:Static local:AppResources.formatAbsentReason}}"
                                            IsVisible="{Binding HasAbsentReason}">
                                        </Label> 
                                    </StackLayout>  
                                </StackLayout>
                            </StackLayout>

                            <StackLayout Orientation="Horizontal" VerticalOptions="FillAndExpand" HorizontalOptions="End">

                                <StackLayout.Padding>
                                    <OnIdiom x:TypeArguments="Thickness">
                                        <OnIdiom.Phone>5, 20, 10, 20</OnIdiom.Phone>
                                        <OnIdiom.Tablet>10, 30, 30, 30</OnIdiom.Tablet>
                                    </OnIdiom>
                                </StackLayout.Padding>

                                <Image 
                                    Style="{StaticResource listviewButtonStyle}"
                                    IsVisible="{Binding EnabledSigning, Source={x:Reference page}}" 
                                    Source="ic_action_yes.png"
                                    VerticalOptions="FillAndExpand"
                                    HorizontalOptions="End">
                                    <Image.GestureRecognizers>
                                        <TapGestureRecognizer  Tapped="OnAttend" />
                                    </Image.GestureRecognizers>
                                    <Image.Margin>
                                        <OnIdiom x:TypeArguments="Thickness">
                                            <OnIdiom.Phone>0, 0, 5, 0</OnIdiom.Phone>
                                            <OnIdiom.Tablet>5, 5, 20, 5</OnIdiom.Tablet>
                                        </OnIdiom>
                                    </Image.Margin>
                                </Image>
                                <Image 
                                    Style="{StaticResource listviewButtonStyle}"
                                    IsVisible="{Binding EnabledSigning, Source={x:Reference page}}" 
                                    Source="ic_action_no.png"
                                    VerticalOptions="FillAndExpand"
                                    HorizontalOptions="End">
                                    <Image.GestureRecognizers>
                                        <TapGestureRecognizer  Tapped="OnAbsent" />
                                    </Image.GestureRecognizers>
                                    <Image.Margin>
                                        <OnIdiom x:TypeArguments="Thickness">
                                            <OnIdiom.Phone>5, 0, 0, 0</OnIdiom.Phone>
                                            <OnIdiom.Tablet>20, 5, 5, 5</OnIdiom.Tablet>
                                        </OnIdiom>
                                    </Image.Margin>
                                </Image>
                            </StackLayout>
                        </StackLayout>

                    </StackLayout>
                </ViewCell.View>
            </ViewCell>

enter image description here


Source: (StackOverflow)

ListView Fast Scroll freezes app on internet images in DataTemplate

I am having internet images in my datatemplate of listview as below. It is a simple mvvm binding, I don't use any code behind at all. When scroll fast on the listview, it gets frozen. it looks like it is caused by multiple downloads. maybe deadlock(?) I am using ffimageloading but I tried using XF image and problem occurs using it as well.

I see in the documentation of ffimageloading, it is mentioned about scrollstatechanged event but I cant find this in xamarin forms listview. It seems like suggested solution is native android level. Of course it makes sense not to have it in XF because of it is android specific. Question is How can I utilize this event if this is the solution? If not, Is there any other solution for this issue?

I tested in UWP, flinging doesn't cause any performance or freeze.

 <DataTemplate>
      <Grid ColumnSpacing="0" >
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="*"></ColumnDefinition>
             <ColumnDefinition Width="2*"></ColumnDefinition>
                                    </Grid.ColumnDefinitions>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="*"></RowDefinition>
                                    </Grid.RowDefinitions>
                                    <ffimageloading:CachedImage  RetryCount="1"   TransparencyEnabled = "false"   CacheDuration = "120"
                                                              LoadingPlaceholder="loading.png"   FadeAnimationEnabled="True"    CacheType="Disk" 
                                                              InputTransparent="True"     ErrorPlaceholder="thumb.png"
                                                    Source="{Binding Images, Converter={StaticResource thumbnailConvertor}}"
                             Aspect="AspectFit"  Grid.Row="0" Grid.Column="0"  />
                                    <StackLayout Orientation="Vertical" Grid.Row="0" Grid.Column="1"  >
                                        <Label Text="{Binding name}"  FontSize="20" FontAttributes="Bold"                            

                                    </StackLayout>
                                </Grid>
                            </DataTemplate>

ScrollStateChanged event in Xamarin Android

_

myListView.ScrollStateChanged += (object sender, ScrollStateChangedEventArgs scrollArgs) => {
  switch (scrollArgs.ScrollState)
  {
    case ScrollState.Fling:
      ImageService.Instance.SetPauseWork(true); // all image loading requests will be silently canceled
      break;
    case ScrollState.Idle:
      ImageService.Instance.SetPauseWork(false); // loading requests are allowed again

      // Here you should have your custom method that forces redrawing visible list items
      _myListView.ForcePdfThumbnailsRedraw();
      break;
  }
};

EDIT: Xamarin forms USING 2.3.5 Pre6

I tried using latest pre release as xamarin claims improvements with fast renderers but it seems like things got even worse. listview is getting frozen instantly even without scrolling when the list appears.


Source: (StackOverflow)

Android FFImageLoading using URI (Xamarin)

I am trying to load the contact images from a cursor, so I have the URI of each image.

But I would like to use the FFImageLoading library to add these images to the view, so that I can easily load placeholders and do a circle transform.

However, I am having difficulty using the library with a URI - I have tried converting the URI to a url using the Path to use the LoadFromURL method, but that has been unsuccessful.

So I am wondering if it would be better to use the LoadImage or LoadStream methods, but I am unsure how best to do so.

Here is what I essentially want to do

    // use FFImageLoading library to asynchronously:
    await ImageService
        .Instance
        .LoadUrl(item.PhotoURL, TimeSpan.FromHours(Settings.ImageCacheDurationHours))  // get the image from a URL
        .LoadingPlaceholder("placeholderProfileImage.png")                                          // specify a placeholder image
        .Transform(new CircleTransformation())                                                      // transform the image to a circle
        .Error(e => System.Diagnostics.Debug.WriteLine(e.Message))
        .IntoAsync(viewHolder.ProfilePhotoImageView);

However, for the images I get from the contacts, I have a Uri and I can load it using the following, but I cant perform a transformation on it:

    var contactUri = ContentUris.WithAppendedId(ContactsContract.Contacts.ContentUri, Contacts[position].LongId);
    var contactPhotoUri = Android.Net.Uri.WithAppendedPath(contactUri, Android.Provider.Contacts.Photos.ContentDirectory);
    viewHolder.ProfilePhotoImageView.SetImageURI(contactPhotoUri);

Also, for relevance here is how I get the contacts:

    var uri = ContactsContract.Contacts.ContentUri;

    string[] projection = {
        ContactsContract.Contacts.InterfaceConsts.Id,
        ContactsContract.Contacts.InterfaceConsts.DisplayName,
        ContactsContract.Contacts.InterfaceConsts.PhotoId
    };

    // CursorLoader 
    var loader = new CursorLoader(activity, uri, projection, null, null, null);
    var cursor = (ICursor)loader.LoadInBackground();

    if (cursor.MoveToFirst())
    {
        do
        {
            Contacts.Add(new Contact
            {

                LongId = cursor.GetLong(cursor.GetColumnIndex(projection[0])),
                LastName = cursor.GetString(cursor.GetColumnIndex(projection[1])),
                PhotoUrl = cursor.GetString(cursor.GetColumnIndex(projection[2]))
            });
        } while (cursor.MoveToNext());
    }

Source: (StackOverflow)

Xamarin Forms FFImageLoading Image not showing

I am trying to use FFImageLoading in one of our Xamarin Forms Projects but I am having some weird issues.

When I try to put Sources="anyvalidimageurl" on the XAML, I get this error:

Invalid XAML: Value cannot be null. Parameter name: 'obj'

This is the XAML:

<ffimageloading:CachedImage HorizontalOptions="Center" 
            WidthRequest="300" 
            HeightRequest="300"
            DownsampleToViewSize="true"
            Source="http://myimage.com/image.png"
            x:Name="imgImage">
</ffimageloading:CachedImage>

I tried to load the image through code, but no image is shown on iOS.


Source: (StackOverflow)

Xamarin.Forms XAML Image as root element

I am new to XAML and everywhere I read about it one would usually use some sort of container as the root view (StackLayout, ContentPage, ContentView, RelativeLayout etc).

But, I run into this XAML that uses Image as its root. Why would we do that?

<?xml version="1.0" encoding="utf-8" ?>
<Image
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:r="clr-namespace:My.Resources;assembly=My.Resources"
    x:Class="My.Views.Buttons.MyView"
        Source="MyImage.png"/>

I would like to replace this Image with FFImageLoading.CachedImage but for that I need to add FFImageLoading xmlns namespace but I cannot since namespaces are inside the Image tag, not outside.


Source: (StackOverflow)

FFImageLoading: Svg not loading

I try to load svg image with FFImageLoading library, but i see empty white image.

Code:

 <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:CrewManagement"
         x:Class="CrewManagement.MainPage"            
         xmlns:abstractions="clr-namespace:ExtendedCells.Forms.Plugin.Abstractions;assembly=ExtendedCells.Forms.Plugin.Abstractions"
         xmlns:ffimageloadingsvg="clr-namespace:FFImageLoading.Svg.Forms;assembly=FFImageLoading.Svg.Forms"
         >

<ContentPage.Content>
<ffimageloadingsvg:SvgCachedImage WidthRequest="200" HeightRequest="200" Source="http://loremflickr.com/600/600/nature?filename=simple.svg"/>
</ContentPage.Content>

Here image: white image


Source: (StackOverflow)

How to reuse cached result in the FFImageLoading on Xamarin.Forms?

I'm trying to load and resize and transform the image in the background while the application main data is loading. I need to do this because some of images are too big and I have a lot of them, so, I thing it's better to prepare all images before showing.

I execute this code in the background: Load the image from Uri:

ImageService.Instance.LoadUrl(uri, TimeSpan.FromDays(60))
            .DownSample(100, 100, false).Preload();

Load the same image and apply additional transformation to it:

ImageService.Instance.LoadUrl(uri, TimeSpan.FromDays(60))
            .DownSample(100, 100, false).Transform(BlurredTransformHere).Preload();

How I could reuse later the result from these cache queries in the CachedImage?

 <forms:CachedImage
    x:Name="Blured"
    Aspect="Fill"
    CacheType="All"
    HorizontalOptions="Fill"
    Opacity="0.3"
    VerticalOptions="Fill"/>     

 <forms:CachedImage
    x:Name="Normal"
    CacheType="All"
    Aspect="AspectFit"
    HorizontalOptions="CenterAndExpand"
    VerticalOptions="CenterAndExpand"/>

Should I add the same config parameters as in the query for each CachedImage? e.g. add DownsampleHeight&W and BlurredTransformation with the same parameters value?


Source: (StackOverflow)

Organize layout xamarin

I have the following command in my layout and I want to organize my layout so that the textview category stays on the FFImageLoading

 <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:gravity="center"
            android:background="#000000"
            android:id="@+id/L_imgF1F2">
            <LinearLayout
                android:layout_width="0dip"
                android:layout_height="125dp"
                android:orientation="vertical"
                android:gravity="bottom"
                android:layout_weight="1"
                android:id="@+id/imgF1"
                android:layout_marginRight="2dp">
                <FFImageLoading.Views.ImageViewAsync
        android:id="@+id/imazhi"
        android:layout_width="100dp"
        android:layout_height="80dp"
        android:scaleType="centerCrop"
        android:layout_marginLeft="4dp"
        android:backgroundTint="#00000000" />
                    <TextView
                        android:id="@+id/CategoryF1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Category"
                        android:textSize="12dp"
                        android:padding="2dp"
                        android:textColor="#ffffff"
                        android:gravity="left" />

              </LinearLayout>

I want my layout to be organized like this, As in the picture enter image description here


Source: (StackOverflow)

How to clear/avoid caching in list item image - Xamain.Forms

I am using FFImageLoading instead of Image in my project for more advanced features like placeholders. In my project, there is a list of images needs to show. So I am using a listview for the same.

<ListView x:Name="membersList" ItemTapped="Handle_ItemTappedMember" HorizontalOptions="FillAndExpand" HasUnevenRows="true" SeparatorVisibility="None" BackgroundColor="#EEEEEE" Grid.Row="0" Grid.Column="0">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ViewCell.View>
                            <StackLayout Orientation="Horizontal" Padding="5,5,5,5" HeightRequest="75" Margin="10,5,10,5" BackgroundColor="White" HorizontalOptions="FillAndExpand">
                                <ffimageloading:CachedImage Source="{Binding imageUrl}" x:Name="patImage" WidthRequest="60" HeightRequest="60" Aspect="AspectFill" VerticalOptions="Center">
                                    <ffimageloading:CachedImage.Transformations>
                                        <fftransformations:CircleTransformation />
                                    </ffimageloading:CachedImage.Transformations>
                                </ffimageloading:CachedImage>
                                <StackLayout Spacing="3" Orientation="Vertical" VerticalOptions="Center" HorizontalOptions="FillAndExpand">
                                    <Label FontAttributes="Bold" FontSize="14" TextColor="#212121" Text="{Binding FullName}" />
                                    <Label FontSize="12" TextColor="#212121" Text="{Binding Relation}" />
                                    <Label FontSize="12" TextColor="#212121" Text="{Binding Pat_ID}" />
                                </StackLayout>
                            </StackLayout>
                        </ViewCell.View>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

My problem is that I don't want to use Caching techniques here since my image from server may be changed without change the URL.

I know how to clear a single image view's cache with FFImageLoading

await CachedImage.InvalidateCache(Image.Source, CacheType.All, true);

But how to achieve this in ListView? I am using Binding property to load images here.


Source: (StackOverflow)

Xamarin: FFImageLoading not showing using inside list view on iOS

I am currently using FFImageLoading library on a listView inside the custom data template.

<ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <ViewCell.ContextActions>
                                <MenuItem Clicked="OnDelete" CommandParameter="{Binding .}" Text="Delete" IsDestructive="True" />
                            </ViewCell.ContextActions>
                            <StackLayout
                                Padding="12,10,12,10" 
                                BackgroundColor="Transparent"
                                Orientation="Horizontal">
                                <Image
                                    DownsampleToViewSize="true"
                                    Aspect="AspectFit"
                                    Source="{Binding FileThumbnail, Converter={StaticResource mimeTypeToImageConverter}}"
                                    WidthRequest="60"
                                    HeightRequest="60">
                                </Image>

Inside the mimeTypeToImageConverter:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string)
        {
            var file = (string)value;     

            if (FileUtilities.IsImageType(file))
            {
                //var fileImageSource = new FileImageSource();
                //fileImageSource.File = file;
                var imageSource = ImageSource.FromFile(file);
                return imageSource;
            } 
            else {
                return ImageSource.FromFile("ic_file_white.png");
            }

        } 
        return null;
    }

I used on android but android works fine. When I change back to Image control, the iOS will show the image.

I really need it to reduce the image size. Does any of you got that problem before.


Source: (StackOverflow)

Xamarin FFImageLoading Usage Clarification

I see we use FFImageLoading like below

var cachedImage = new CachedImage() {
    HorizontalOptions = LayoutOptions.Center,
    VerticalOptions = LayoutOptions.Center,
    WidthRequest = 300,
    HeightRequest = 300,
  ...
    Source = <url or asset or resource location>

};

or in XAML:

<ffimageloading:CachedImage 
  HorizontalOptions="Center" VerticalOptions="Center"
    WidthRequest="300" HeightRequest="300"
    DownsampleToViewSize="true"
    Source = "<url or asset or resource location>>
</ffimageloading:CachedImage>

, so, I replaced all instances of Image in my UWP project and ImageView in my Android project with CachedImage.

But after reading through FFImageLoading documentation, I also see lots of cases where images are loaded using ImageService. For example:

ImageService.Instance.LoadUrl(urlToImage).Into(_imageView);
ImageService.Instance.LoadCompiledResource(nameOfResource).Into(_imageView);
...
  • What is the difference between these two ways?

  • Why would I use one over the other?


Source: (StackOverflow)

Xamarin Android FFImageLoading ImageService.Instance.LoadUrl() System.NullReferenceException

I've got a strange problem with FFImageLoading. Compiler don't show any error, but while application is starting on device, there is thrown an exception: System.NullReferenceException.


Code:

C#

private void setUserImage()
{
    ImageService.Instance.Initialize();
    imgThunbailUsername = FindViewById<ImageViewAsync>(Resource.Id.imgDisplay);
    string url = @"https://lh4.googleusercontent.com/-Lfgi-xEMwuk/VNWoy8EDWcI/AAAAAAAAACk/rwsluNfhSZY/w1486-h832-no/photo.jpg";

    ImageService.Instance.LoadUrl(url)
        .Retry(3, 200)
        .DownSample(60, 60)
        .Into(imgThunbailUsername); // compiler points here with an exception
}

XML

<FFImageLoading.Views.ImageViewAsync
  android:id="@+id/imgDisplay"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:scaleType="fitCenter" />

I'd be thankful for any tip, idea, or even another good tool for images in Xamarin.


Source: (StackOverflow)

Load image from URI into Button in Xamarin.Forms using FFImageLoading

Is there any way to load Image into Xamarin.Forms Button from URL? It seems that button itself only support FileImageSource.

Sure, I can download image and then manually put it into Button, but I hope someone has done this already in reusable fashion :)


Source: (StackOverflow)