首页 > 解决方案 > 从 .net Web API 检索多个图像并在 Xamarin 表单中填充的最佳方法

问题描述

这是我用来获取单个图像的代码。此代码循环运行以填充图像并且正在运行。但有时如果获取图像有延迟。应用程序卡在填充数据中

            var resp = await Client.GetAsync(imageUrl);
            if (resp.IsSuccessStatusCode)
            {
                imageData = await resp.Content.ReadAsByteArrayAsync();
            }

这是调用单个产品图像下载的循环:

 List<Task> tasks = new List<Task>();
            foreach (var product in productsList)
            {
                var task = DownloadImage(eImageType.Brand, product);
                tasks.Add(task);
            }

动态构建图像对象的代码

        foreach(var brand in brands)
        {
            brand.ImageSource = ImageSource.FromStream(() =>
            {
                if (brand.ImageData != null)
                    return new MemoryStream(brand.ImageData);
                else
                    return null;
            });
        }

在 XAMLS 中显示图像视图的代码

              <AbsoluteLayout>
                                            <ffimage:CachedImage Source="blugegb" HorizontalOptions="Fill"
                                                   DownsampleWidth="180"
                                                   DownsampleUseDipUnits="True"
                                                   AbsoluteLayout.LayoutBounds="0,0,1,1" AbsoluteLayout.LayoutFlags="All"
                                                       VerticalOptions="Fill"
                                                       Aspect="AspectFill"/>
                                            <ffimage:CachedImage Source="{Binding ImageSource}" HorizontalOptions="Fill"
                                                                 DownsampleWidth="100"
                                                                 DownsampleUseDipUnits="True"
                                                   AbsoluteLayout.LayoutBounds=".5,.5,.8,.8" AbsoluteLayout.LayoutFlags="All"
                                                       VerticalOptions="Fill"
                                                       Aspect="AspectFit"/>
                                        </AbsoluteLayout>

标签: xamarinasp.net-web-apixamarin.forms

解决方案


如果您使用的是 FFImageLoading 那么它非常简单,您所要做的就是:

  <ffimage:CachedImage Source="{Binding ImageSource}" HorizontalOptions="Fill"
                                                             DownsampleWidth="100"
                                                             DownsampleUseDipUnits="True"
                                               AbsoluteLayout.LayoutBounds=".5,.5,.8,.8" AbsoluteLayout.LayoutFlags="All"
                                                   VerticalOptions="Fill"
                                                   Aspect="AspectFit"/>

在其源中提供到 CachedImage 的绑定,然后直接将 URL 作为绑定传递给源,例如:

public string ImageSource {get; set;}
//SomeWhere in your code 
ImageSource="https://images.pexels.com/photos/807598/pexels-photo-807598.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940/abcd.jpg";

推荐阅读