简体   繁体   中英

How to randomly Display Images from ArrayList<Integer>

I'm trying to randomly display images from an Array. The canvas is rendering but my images are not displaying on the canvas at all. My Drawables are title "one, two, three, four, five"

this is how I initialized my array int[] array1;

this is my convert function

public static int[] convertIntegers(List<Integer> integers) {
    int[] ret = new int[integers.size()];
    Iterator<Integer> iterator = integers.iterator();
    for (int i = 0; i < ret.length; i++) {
        ret[i] = iterator.next().intValue();
    }
    return ret;
}

This is my render method. The canvas displays but the images do not and I am not get any errors.

public void render(Canvas canvas) {

    if (canvas != null) {
        canvas.drawRGB(234, 237, 235);


     ArrayList<Integer> list = new ArrayList<Integer>();

        Random random = new Random();

        int[] images = new int[] { R.drawable.one, R.drawable.two,
                R.drawable.three, R.drawable.four, R.drawable.five };

        for (int i = 0; i < 5; i++) { 

            while (true) {
                int next = random.nextInt(5);
                if (!list.contains(next)) {
                    list.add(images[next]);
                    break;
                }
            }
        }

        array1 = convertIntegers(list);

    }
}

I want the Array to display the images randomly throughout the view. Eventually I want each image to have the int value of it's name (ie drawable "one" will have value 1) and the Array will randomly display images until the total is 50. But right now I'm just trying to get the images to display on the Canvas.

I'm new to Android dev but was using this thread to help android how to get 4 images in array from ten array of image randomly

Appreciate any help

EDIT: not sure if this will help but I'm using SurfaceView and this in in my MainGamePanel Activity.

You are following that SO answer, yet you don't use the Shuffle method on the List, but instead do a double loop to re-sort the numbers.

The reason why your images are not being drawn on the Canvas is because you never draw them. You create the list and randomize the values, but you never draw them on the Canvas.

You should do like this after you get the array (I didn't test it but should be similar to this):

int x = 0;
int y = 0;
for (int i=0; i<array.length; i++) {
  Bitmap bmp = BitmapFactory.decodeResource(getResources(), array1[i]);            
  canvas.drawBitmap(bmp, x, y, null);
  x += bmp.getWidth();
}

EDIT: I just realized you are doing all the calculation on the onRender() method. You probably want to move everything but the drawing outside the method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM