在应用程序启动时自动保存和检索背景图像

时间:2012-06-03 19:55:18

标签: c# windows-phone-7

在我的Windows Phone 7应用程序中,我创建了一个可以改变背景的按钮。数量。默认情况下我有一个背景图片。我需要的是,如果用户改变了背景(使用上面的按钮),我希望该图像应该被隔离的存储保存或记住。然后当应用程序再次启动时,该特定图像(用户上次选择)应该是我的应用程序的背景图像。现在问题是,我无法检索图像(但能够保存它),并且不知道如何在应用程序启动时自动将该图像作为背景图像(不想使用任何按钮来保存或检索,必须是自动的)。有谁能够帮我?非常感谢您的辛勤工作!

private void button1_Click(object sender, RoutedEventArgs e)
    {
        string imguri = "";

        click_count = click_count % 4;
        switch (click_count)
        {
            case 0: imguri = "Images/image4.png"; break;
            case 1: imguri = "Images/image3.jpg"; break;
            case 2: imguri = "Images/image2.png"; break;
            case 3: imguri = "Images/image1.jpg"; break;

        }
        click_count++;

        BitmapImage bitmapImage = new BitmapImage(new Uri(imguri, UriKind.Relative));
        ImageBrush imageBrush = new ImageBrush();
        imageBrush.ImageSource = bitmapImage;
        var app = Application.Current as App;
        this.LayoutRoot.Background = imageBrush;
        app.appbrush = imageBrush;
        app.backchanged = true;

        string filename = "Images/app.jpg";
        StreamResourceInfo sr = Application.GetResourceStream(new Uri(filename, UriKind.Relative));

        bitmapImage.SetSource(sr.Stream);
        WriteableBitmap wb = new WriteableBitmap(bitmapImage);

        using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
        {
            myIsolatedStorage.CreateDirectory("Images");

            if (myIsolatedStorage.FileExists(filename))
            {
                myIsolatedStorage.DeleteFile(filename);
            }
            IsolatedStorageFileStream filestream = myIsolatedStorage.CreateFile(filename);
            Extensions.SaveJpeg(wb, filestream, wb.PixelWidth, wb.PixelHeight, 0, 100);
            filestream.Close();
        }
    }

1 个答案:

答案 0 :(得分:0)

尝试使用此代码加载图片并将其指定给背景:

IsolatedStorageFile Store = IsolatedStorageFile.GetUserStoreForApplication();

if (Store.FileExists("Images/app.jpg"))
{
    try
    {
        using (IsolatedStorageFileStream Stream = new IsolatedStorageFileStream(Path, FileMode.Open, FileAccess.Read, Store))
        {
            if (Stream.Length > 0)
            {
                BitmapImage Image = new BitmapImage();
                Image.SetSource(Stream);
                this.LayoutRoot.Background = Image;
            }
        }
    }
    catch (Exception)
    {            
    }
}