在Xamarin/C#中从URL加载的UIImage

Jas*_*ley 25 c# uiimage xamarin.ios ios xamarin

这篇博客文章回答这个问题已有4年了.

有没有一种标准的方法来创建一个带有URL图像的UIImage?就像是:

UIImage image = UIImage.FromFile("http://foo.com/bar.jpg");
Run Code Online (Sandbox Code Playgroud)

我觉得我可能错过了一些非常简单的东西.

pou*_*pou 57

不是单行,但只有很少的线,你可以自己滚动.例如

static UIImage FromUrl (string uri)
{
    using (var url = new NSUrl (uri))
    using (var data = NSData.FromUrl (url))
        return UIImage.LoadFromData (data);
}
Run Code Online (Sandbox Code Playgroud)

这些调用包括来自的调用UIImage是线程安全的.


Pav*_*ich 27

使用新的await/async支持,您可以:

public async Task<UIImage> LoadImage (string imageUrl)
        {
            var httpClient = new HttpClient();

            Task<byte[]> contentsTask = httpClient.GetByteArrayAsync (imageUrl);

            // await! control returns to the caller and the task continues to run on another thread
            var contents = await contentsTask;

            // load from bytes
            return UIImage.LoadFromData (NSData.FromArray (contents));
        }
Run Code Online (Sandbox Code Playgroud)

你打电话给这个:

someYourUIImageObjectOnUI.Image = await this.LoadImage ("some image url");
Run Code Online (Sandbox Code Playgroud)

  • byte [] contents =等待httpClient.GetByteArrayAsync(imageUrl); (5认同)

Jas*_*son 5

您希望确保加载图像异步,以便不阻止UI线程.MonoTouch.Dialog包含一个可以使用的ImageLoader(参见sec 5.3)类.

还有一些UrlImageStore的变体可以帮助处理异步加载图像.

最后,如果您想手动完成,可以使用Xamarin配方.