How to load an image at random

ciginfo

Well-Known Member
Licensed User
Longtime User
Hello,
In Sub Activity_Create I load several images with this code.
Bmp_01 = LoadBitmap (File.DirAssets "Image_01.png")
Bmp_02 = LoadBitmap (File.DirAssets "Image_02.png")
Bmp_03 = LoadBitmap (File.DirAssets "Image_03.png")
etc ...
I want to load into a ImageView one of these images, but randomly. What is the code to load the image at random?
Thank you
 

Inman

Well-Known Member
Licensed User
Longtime User
You can store the names of image files in a list and then use RND() function to generate a random number between 0 and list size. Then using that number as the index, you can get a random image name from the list.
 
Upvote 0

klaus

Expert
Licensed User
Longtime User
If your bitmaps are big it wouldn't be a good solution to define several bitmaps and store them in memory.
You could generate a random number n between the numbers of the files and then load this file to the ImageView with:
B4X:
n = Rnd(1, 4) ' in your case between 1 and 3
ImageView1.Bitmap = LoadBitmap(File.DirAssets, "Image_" & NumberFormat(n, 2, 0) & ".png")
The NumberFormat function is used to make sure that leading zeros are added to n.

Best regards
 
Last edited:
Upvote 0

ibra939

Active Member
Licensed User
Longtime User
very nice
 
Upvote 0
Top