我的应用程序中有一个组件需要预加载某些图像。我的想法是我应该将网络上的所有图像下载到位图对象中,然后将它们用作我的图像中的源。最简单的方法是什么?我已经编写了一些代码来下载图像,但它似乎不适用于多个图像:
HttpClient client = new HttpClient();
NetResult result;
try
{
Debug.WriteLine("Starting call to " + Url);
HttpResponseMessage response = await client.GetAsync(Url);
response.EnsureSuccessStatusCode();
result = await this.processContent(response.Content);
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
Debug.WriteLine("Unable to load " + Url);
result = new NetResult(NetResultStatus.Failure, "Could not connect to " + Url + ".");
}
...
ProcessContent 的工作方式如下:
public override async Task<NetResult> processContent(HttpContent content)
{
InMemoryRandomAccessStream randomAccessStream = null;
if (content != null && !Constants.FakeInternet)
{
byte[] img = await content.ReadAsByteArrayAsync();
// Transform to a stream
randomAccessStream = new InMemoryRandomAccessStream();
DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
writer.WriteBytes(img);
await writer.StoreAsync();
}
_m = new ManualResetEvent(false);
(Application.Current as App).UIDispatcher.DispatchAsync(() =>
{
// Create bitmap image
image = new BitmapImage();
NetImage i = (NetImage)this;
Debug.WriteLine("Creating Image " + Url);
image.ImageFailed += ImageFailed;
image.ImageOpened += ImageOpened;
image.SetSource(randomAccessStream);
});
_m.WaitOne();
return await base.processContent(content);
}
void ImageOpened(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
Debug.WriteLine("Image opened: " + Url);
_m.Set();
}
void ImageFailed(object sender, Windows.UI.Xaml.ExceptionRoutedEventArgs e)
{
Debug.WriteLine("Image failed: " + Url);
image = null;
ConnectionState = ConnectionState.Failed;
_m.Set();
}
是否有一个内置的 API 可以用来从网络将 PNG 下载到位图对象中?我想其中一件烦人的事情是我必须在 UI 线程上解码位图……这是为什么呢?