xamarin - 从 .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>
解决方案
如果您使用的是 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";
推荐阅读
- javascript - 如何防止 MathJax 中的公式触摸事件?
- python - 使用我的 django 应用程序在 mailchimp 中发送模板
- php - PHP - 在选择框中设置默认年份
- angular - Angular 7中订阅方法内的代码覆盖行
- javascript - Web 从多个页面抓取内容,而无需通过 webdriver 访问每个页面
- python - 在 Python 3.7 中使用 try 和 except 代替 isinstance
- python - 无法弄清楚我在第 1 行遇到的语法错误-python
- c - C - 为空指针赋值
- bash - 使用 sed 将日期格式从 DD/MM/YYYY 更改为 YYYY-MM-DD
- c - 使用德摩根定律在 C 中编写表达式