I've been trying to draw an image onto a canvas in my metro app but nothing has appeared so far. Here is my code:
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);
When I use the line
blueRectangle.Fill = new SolidColorBrush(Colors.Blue);
instead of the one using the ImageBrush I get a blue rectangle like I intended so I think I must be doing something wrong with the ImageBrush.
I plan on using the images as sprites in a game when I learn how to draw them so I have to be able to manipulate them using c#.
Thanks for you help!
Edit: I've changed the code to access the roaming application data but I'm still getting a file not found exception. (the file is in the correct place)
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);
I eventually figured it out. Here's what I have for code now.
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);
I ended up using a StorageFolder and created the BitmapImage using a Stream instead of from a uri.