在Xamarin Monotouch的uiimageview中异步加载图像

时间:2014-02-24 06:10:10

标签: c# asynchronous xamarin.ios xamarin

我有表格单元格,因为我在水平滚动视图中显示多个图像,我需要异步将图像加载到imageview中,这意味着如果没有加载图像,我需要放置默认的placefolder.png文件。

如果图像已加载,我需要将placeholder.png替换为已加载的图像。

任何人都可以帮助我..

_image = new UIImageView(FromUrl(contentItem.FilePath, cachedImages)) { Tag = 1001 };
_imagePath = contentItem.FilePath;
_image.Frame = new RectangleF(x, 0, 250, _image.Image.CGImage.Height);
x = x + (Convert.ToInt32( Bounds.Width));
        scrollwidth = scrollwidth + Convert.ToInt32( Bounds.Width);
_scrollView.ContentSize = new SizeF (scrollwidth, _image.Image.CGImage.Height);
_scrollView.Add (_image);

1 个答案:

答案 0 :(得分:1)

由于它是一个表格单元格而且你无法确定任务完成时单元格是否仍然相同,我会创建一个与此类似的下载任务:

    public async static Task<string> DownloadImage(string fileWebAddress, string localPath)
    {
        await new WebClient ().DownloadFileTaskAsync (url, fileName);
        return localPath;
    }

然后在创建单元格时,首先要检查是否已将图像下载到本地存储:

if (File.Exist(contentItem.FilePath))
{
    SetImage(_image, contentItem.FilePath);
}

如果没有,则启动异步下载,当它返回时,检查该任务是否属于当前单元格(contentItem不能是本地函数变量,它必须是可以更改的单元格变量):

else
{
        DownloadImage(contentItem.WebPath, contentItem.FilePath).ContinueWith (t =>
            {
                if (contentItem.FilePath == t.Result)
                {
                    SetImage(_image, t.Result);
                }
            });
}