I’m still learning the basics and I’m making a “Random Character Generator” that creates basic stats for the ‘World’s dullest hero’.
I’ve inlcuded an Image box (named charbox) which, on character generation, is supposed to display one of three .jpg files.
I have added all 3 jpgs to my solution (they’re all listed in the images folder of the Solution Explorer) but I can’t get the button to pick one to display.
I’m using a switch (which may very well have a completely wrong syntax) which should use a random integer I’ve declared as “img” with a range of (0,3).
Here’s the code, which I pulled from another site, but it doesn’t work in my program:
switch (img)
{
case 1:
charbox.Source = new BitmapImage(new Uri(@"C:\Users\Otis\documents\visual studio 2010\Projects\WpfApplication2\WpfApplication2\Images\guy1.jpg", UriKind.Relative));
break;
case 2:
charbox.Source = new BitmapImage(new Uri(@"C:\Users\Otis\documents\visual studio 2010\Projects\WpfApplication2\WpfApplication2\Images\guy2.jpg", UriKind.Relative));
break;
default:
charbox.Source = new BitmapImage(new Uri(@"C:\Users\Otis\documents\visual studio 2010\Projects\WpfApplication2\WpfApplication2\Images\guy3.jpg", UriKind.Relative));
break;
}
Any idea how I can make this work?
-Edit-
I have done some looking, and changed my image selection code to:
#region Image Selection
bmguy.BeginInit();
switch (img)
{
case 0:
bmguy.UriSource = new Uri(@"C:\Users\Otis\Pictures\guy1.jpg");
break;
case 1:
bmguy.UriSource = new Uri(@"C:\Users\Otis\Pictures\guy2.jpg");
break;
case 2:
bmguy.UriSource = new Uri(@"C:\Users\Otis\Pictures\guy3.jpg");
break;
}
bmguy.EndInit();
charbox.Source = bmguy;
#endregion
Where bmguy is a bitmapimage declared as a global variable and switch (img) still uses a 1-3 random number.
So, now when I click generate the image loads guy1.jpg. But it’s always guy1.jpg and if I click generate a second time it throws up an error about bitmap initialisation only occuring once.
Should I be using three seperate bitmapimages or can I use the one and change the file path as I attemped in my switch?
You’re trying to reinitialize the bitmap every time. Just assign it to the picture box the first time.