使用SDWebImageDownloader Xamarin在UICollectionView中缓存图像并加载滚动

时间:2016-11-10 08:02:32

标签: ios caching xamarin uicollectionviewcell sdwebimage

我有一个带有图像的UICollectionView,这些图像是从URL和标题下载的。我这样做的事情如下: -

internal void UpdateCell(ProfileValues mdata)
        {


            var mUrl = "someurl";

   var manager = SDWebImageManager.SharedManager;
   manager.ImageCache.MaxCacheAge = 86400;
            SDWebImageDownloader mDownloader = manager.ImageDownloader;

            var authToken = "SomeToken"";


            mDownloader.SetHttpHeaderValue(authToken, "Authorization");
            mDownloader.SetHttpHeaderValue("application/json; odata=verbose", "Accept");
            mDownloader.SetHttpHeaderValue("f", "X-FORMS_BASED_AUTH_ACCEPTED");


            try
            {
                mDownloader.DownloadImage(
                 url: new NSUrl(mUrl),
     options: SDWebImageDownloaderOptions.ProgressiveDownload,
                progressBlock: (receivedSize, expectedSize) =>
                {
                    // Track progress...
                },
                completedBlock: (image, data, error, finished) =>
                {

                    if (image != null && finished)
                    {
                        InvokeOnMainThread(() =>
                        {

                            this.imgProfilePic.Image = image;
                        });

                    }
                    if (error != null)
                    {
                        InvokeOnMainThread(() =>
                        {
                            this.imgProfilePic.Image = errorImage;
                            this.imgProfilePic.BackgroundColor = UIColor.FromRGB(52, 31, 71);
                            //this.imgProfilePic.Layer.CornerRadius = this.imgProfilePic.Frame.Size.Width / 2;
                            this.imgProfilePic.ClipsToBounds = true;
                            this.imgProfilePic.Layer.BorderWidth = 3.0f;
                            this.imgProfilePic.Layer.BorderColor = UIColor.White.CGColor;
                        });
                    }
                }


              );
            }
            catch (Exception ex)
            {
            }
        }

但是在每个滚动条上都会重新加载单元格,并且每次都会下载图像。如何在滚动时缓存图像并从缓存中加载图像?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

使用FFImageLoading包&使用 cachedImage 类的图像

var cachedImage = new CachedImage() {
    HorizontalOptions = LayoutOptions.Center,
    VerticalOptions = LayoutOptions.Center,
    WidthRequest = 300,
    HeightRequest = 300,
    CacheDuration = TimeSpan.FromDays(30),
    DownsampleToViewSize = true,
    RetryCount = 0,
    RetryDelay = 250,
    TransparencyEnabled = false,
    Source = "http://loremflickr.com/600/600/nature?filename=simple.jpg",
    CacheKeyFactory = new CustomCacheKeyFactory(),
};