在metro应用程序中将图像绘制到画布

时间:2012-08-09 03:19:05

标签: c# xaml windows-8 microsoft-metro imagebrush

我一直在尝试在我的地铁应用程序中将图像绘制到画布上,但到目前为止还没有出现任何内容。这是我的代码:

    Rectangle blueRectangle = new Rectangle();
        blueRectangle.Height = 100;
        blueRectangle.Width = 200;
        ImageBrush imgBrush = new ImageBrush();
        imgBrush.ImageSource = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri("C:\\Users\\Public\\Pictures\\dock.jpg"));
        blueRectangle.Fill = imgBrush;
        paintCanvas.Children.Add(blueRectangle);

当我使用

行时
      blueRectangle.Fill = new SolidColorBrush(Colors.Blue);

而不是使用ImageBrush的那个我得到一个像我想要的蓝色矩形所以我认为我必须对ImageBrush做错了。

当我学习如何绘制它们时,我计划将图像用作游戏中的精灵,因此我必须能够使用c#来操作它们。

谢谢你的帮助!

编辑: 我已经更改了代码以访问漫游应用程序数据,但我仍然得到一个未找到文件的异常。 (文件在正确的位置)

    ApplicationData appData = ApplicationData.Current;

        try
        {
            StorageFile sourceFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/dock.jpg"));
            await sourceFile.CopyAsync(appData.RoamingFolder);
        }
        catch (Exception ex)
        {
            // If images have already been copied the CopyAsync() methods aboev will fail.
            // Ignore those errors.
            System.Diagnostics.Debug.WriteLine(ex.ToString());
        }

        Rectangle blueRectangle = new Rectangle();
        blueRectangle.Height = 100;
        blueRectangle.Width = 200;

        // Create an ImageBrush
        ImageBrush imgBrush = new ImageBrush();

        imgBrush.ImageSource = new BitmapImage(new Uri("ms-appdata:///roaming/dock.png"));

        // Fill rectangle with an ImageBrush
        blueRectangle.Fill = imgBrush;
        //blueRectangle.Fill = new SolidColorBrush(Colors.Blue);
        paintCanvas.Children.Add(blueRectangle);

2 个答案:

答案 0 :(得分:2)

我最终弄明白了。这就是我现在的代码。

StorageFile file;
StorageFolder InstallationFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;      

string filePath = @"Assets\dock.jpg";
file = await InstallationFolder.GetFileAsync(filePath);
IRandomAccessStream dockpic = await file.OpenAsync(0);
BitmapImage dockimage = new BitmapImage();
dockimage.SetSource(dockpic);

Rectangle blueRectangle = new Rectangle();
blueRectangle.Height = 100;
blueRectangle.Width = 200;
// Create an ImageBrush
ImageBrush imgBrush = new ImageBrush();
imgBrush.ImageSource = dockimage;

// Fill rectangle with an ImageBrush
blueRectangle.Fill = imgBrush;
paintCanvas.Children.Add(blueRectangle);

我最终使用了StorageFolder并使用Stream而不是uri创建了BitmapImage。

答案 1 :(得分:1)

您无法通过Metro风格应用以这种方式访问​​本地数据。有关您可以访问本地数据的方法,请参阅accessing local dataApplication data sample上的这篇文章。