5

プロジェクトのアセット フォルダーに、アプリの開始時にメモリに読み込む必要がある画像がたくさんあります。CPU の負荷と時間を削減するための最善の方法は何ですか。

私はこれをやっています:

for (int i = 0; i < 10; i++)
        {
            var smallBitmapImage = new BitmapImage
            {
                UriSource = new Uri(string.Format("ms-appx:/Assets/Themes/{0}/{1}-small-digit.png", themeName, i), UriKind.Absolute)
            };

            theme.SmallDigits.Add(new ThemeDigit<BitmapImage> { Value = i, BitmapImage = smallBitmapImage, Image = string.Format("ms-appx:/Assets/Themes/{0}/{1}-small-digit.png", themeName, i) });
        }

そして、この BitmapImage をイメージ コントロールにバインドします。

しかし、UriSource を設定すると実際に画像がメモリに読み込まれるかどうかは正確にはわかりません。

BitmapImage の SetSourceAsync プロパティも確認しました。しかし、私のコンテキストでそれを使用する方法がわかりません。SetSourceAsyncプロパティまたは画像をロードする最良の方法を教えてください....

ありがとう

4

2 に答える 2

1

間違った答えが表示されたくなかったので、10 秒後に別の答えを追加する必要があります...

例:

BitmapImage image1 = LoadImageToMemory("C:\\image.png");
BitmapImage image2 = LoadImageToMemory(webRequest.GetResponse().GetResponseStream());

public BitmapImage LoadImageToMemory(string path)
{
        BitmapImage image = new BitmapImage();

        try
        {
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            System.IO.Stream stream = System.IO.File.Open(path, System.IO.FileMode.Open);
            image.StreamSource = new System.IO.MemoryStream();
            stream.CopyTo(image.StreamSource);
            image.EndInit();

            stream.Close();
            stream.Dispose();
            image.StreamSource.Close();
            image.StreamSource.Dispose();
        }
        catch { throw; }

        return image;
}

// または System.Net.WebRequest().GetResponse().GetResponseStream() を使用する

public BitmapImage LoadImageToMemory(System.IO.Stream stream)
    {
        if (stream.CanRead)
        {
            BitmapImage image = new BitmapImage();

            try
            {
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.StreamSource = new System.IO.MemoryStream();
                stream.CopyTo(image.StreamSource);
                image.EndInit();

                stream.Close();
                stream.Dispose();
                image.StreamSource.Close();
                image.StreamSource.Dispose();
            }
            catch { throw; }

            return image;
        }

        throw new Exception("Cannot read from stream");
}
于 2012-12-11T11:08:38.200 に答える