自this question已用this blog post回答已有4年了。從Xamarin/C中的URL加載的UIImage#
有沒有一種標準的方式來創建一個URL與圖像的UIImage?例如:
UIImage image = UIImage.FromFile("http://foo.com/bar.jpg");
我覺得我可能錯過了一些非常簡單的事情。
自this question已用this blog post回答已有4年了。從Xamarin/C中的URL加載的UIImage#
有沒有一種標準的方式來創建一個URL與圖像的UIImage?例如:
UIImage image = UIImage.FromFile("http://foo.com/bar.jpg");
我覺得我可能錯過了一些非常簡單的事情。
不是一句話,但只有很少幾行你可以自己推出。例如。
static UIImage FromUrl (string uri)
{
using (var url = new NSUrl (uri))
using (var data = NSData.FromUrl (url))
return UIImage.LoadFromData (data);
}
這些調用包括UIImage
中的調用都是線程安全的。
你想確保你加載的圖像異步,以便你不會阻止你的UI線程。 MonoTouch.Dialog包含您可以使用的ImageLoader(參見5.3)類。
這裏還有UrlImageStore的一些變化,以幫助異步加載圖像。
最後,如果您想手動執行此操作,則可以使用Xamarin Recipe。
有了新的await /異步支持,你可以這樣做:
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));
}
,你調用此方法:
someYourUIImageObjectOnUI.Image = await this.LoadImage ("some image url");
byte [] contents = await httpClient.GetByteArrayAsync(imageUrl); – winnicki
我嘗試了上面,它看起來像一個偉大的想法,但我得到: 無法隱式轉換類型System.Threading.Tasks.Task<MonoTouch.UIKit.UIImage>' to
Monotouch.UIKit.UIImage」
[找到了解決辦法] 問題是因爲
obj.Image =等待this.LoadImage(imageUrl) 也必須在標記爲async的方法中。 然後它的工作!
感謝
當我嘗試這一個URL,例如https://www.google.ca/images/srpr/logo11w.png我得到「無法初始化類「MonoTouch.Foundation的一個實例。 NSUrl':原生的'initWithString:'方法返回nil。「任何想法爲什麼會發生? – user2320724
'NSUrl'會拋出(在ObjC中返回'nil'),那麼提供的URL是無效的(不符合RFC 2396)。請參閱Apple的文檔@ https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html#//apple_ref/occ/instm/NSURL/initWithString: – poupou