2012-08-09 62 views
0

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

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); 

,而不是一个使用的图像刷我得到一个蓝色的矩形像我预期的,所以我想我必须做一些错误的图像刷。

我计划在游戏中使用图像作为精灵,当我学习如何绘制它们时,我必须能够使用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

我终于明白了。这是我现在的代码。

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和使用流,而不是从一个URI创建的BitmapImage。

1

您无法以Metro风格应用程序的方式访问本地数据。有关如何访问本地数据的方法,请参见accessing local dataApplication data sample上的这篇文章。

+0

感谢您的示例。我试过使用该方法来访问应用程序的漫游数据,但我得到一个FileNotFoundException。 – connor 2012-08-09 14:08:58