How to load images randomly?

1

How do I randomly load images in the background of an app page, so that every time the user enters a particular page the background toggles between images?

How do I proceed to do this?

    
asked by anonymous 11.07.2014 / 03:10

1 answer

1

Create a private method on the page that will have this effect in the background, in case the example is named Pagina1 .

private void RandomImage()
{
      Random random = new Random();
      String nameim = random.Next(1, 3).ToString() + ".jpg";
      Uri uri = new Uri("ms-appx:/Assets/" + nameim, UriKind.RelativeOrAbsolute);
      ImageBrush img = new ImageBrush();
      img.ImageSource = new BitmapImage(uri);
      this.Background = img;
}

Why do I put in Next(1,3) of Random ?

Within pasta Assests has two images with the respective names 1.jpg and 2.jpg , so in the example I only have these images numbered to create the random effect. If you have more images then you will have to increase the number 3 to the number of (imagens + 1) and realize that they are sequence numbers.

In order to work place this RandomImage() method inside your Construtor below InitializeComponent() :

public Pagina1()
{
     this.InitializeComponent();
     this.RandomImage();
}

From this every time you load Pagina1 , background will change according to the number generated by Random .

Reference

11.07.2014 / 04:36