1

在我的应用程序中,我需要下载几张图片,这些图片是60kb顶部。

我一直在做的事情是:

image.Image = UIImage.LoadFromData (NSData.FromUrl (new NSUrl("http://url")));

这可行,但下载图像需要很长时间。有没有更好/更快的方法来解决这个我不知道的?

图像下载发生在ViewDidLoad ()方法中,这会导致在转到此视图控制器之前出现令人不舒服的长时间停顿。

4

2 回答 2

2

MonoTouch.Dialog 包括一个ImageLoader(第 5.3 节)类,它将处理图像的背景加载,并且可以在下载“真实”图像时分配默认图像。它可能不一定更快,但它应该对用户更敏感。

image.Image = ImageLoader.DefaultRequestImage( new Uri(uriString), this)

正如@poupou 所指出的,第二个参数必须是对实现 IImageUpdated 的类的引用。

于 2013-05-23T01:12:43.640 回答
1

使用相同 API 的快速而肮脏的方法(改编自我拥有的一些代码)将是:

// Show a "waiting / placeholder" image until the real one is available
image.Image = ...
UIImage img = null;
// Download the images outside the main (UI) thread
ThreadPool.QueueUserWorkItem (delegate {
    UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
    using (NSUrl nsurl = new NSUrl (url))
    using (NSData data = NSData.FromUrl (nsurl)) {
        UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
        // we might not get any data, e.g. if there's no internet connection available
        if (data != null)
            img = UIImage.LoadFromData (data);
    }
    // finally call the completion action on the main thread
    NSRunLoop.Main.InvokeOnMainThread (delegate {
        // note: if `img` is null then you might want to keep the "waiting"
        // image or show a different one
        image.Image = img;
    });
});

另一件可能有帮助的事情是缓存您下载的图像(例如离线模式)——但这对于您的应用程序来说可能是不可能的。

在这种情况下,您将首先检查缓存是否有您的图像,如果没有,请确保在下载后保存它(所有这些都在后台线程中完成)。

于 2013-05-23T01:44:16.137 回答