0

我的应用程序中有一个组件需要预加载某些图像。我的想法是我应该将网络上的所有图像下载到位图对象中,然后将它们用作我的图像中的源。最简单的方法是什么?我已经编写了一些代码来下载图像,但它似乎不适用于多个图像:

 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 线程上解码位图……这是为什么呢?

4

1 回答 1

0

我不知道 WinRT API 可以为您节省一些下载 PNG 和创建 BitmapImage 的步骤。这并不意味着不存在。

您可能会发现查看XAML 图像示例中的场景 4 会有所帮助。它在后台线程上异步计算分形,然后在 WriteableBitmap 中显示结果。这将使您脱离 UI 线程。

于 2013-01-11T18:18:43.893 回答