如何在UIImageView中显示随机图像每次重置时

时间:2014-05-31 20:47:45

标签: ios objective-c uiimageview nsarray

我目前正在制作游戏。我有一个UIImageView从右向左滚动,一旦它离开ViewController图像重置在右边并向左滚动,这当前设置为显示" image1"我希望将其更改为每次从右侧重置时从一组5中随机显示不同的图像。

这是我的方法:

- (void)PlacePipe{

    RandomTopPipePosition = arc4random() %350;
    RandomTopPipePosition = RandomTopPipePosition - 228;
    RandomBottomPipePosition = RandomTopPipePosition + 660;

    PipeTop.center = CGPointMake(340-10, RandomTopPipePosition);
    randomImagebottom.center = CGPointMake(340-10, RandomBottomPipePosition);

}

我要随机添加到此UIImageView的图片的名称是-toppipestyleone.png,toppipestyletwo.png,toppipestylethree.png,toppipestylefour.png,toppipestylefive.png"。

我不确定在做到这一点的最佳路线上,我看着用数组做这件事,但我不确定如何设置数组甚至是随机调用图像。

1 个答案:

答案 0 :(得分:4)

您可以按照您的考虑将图像名称放在数组中,例如

NSArray *imageNameArray = [[NSArray alloc] initWithObjects:@"toppipestyleone.png", @"toppipestyletwo.png", @"toppipestylethree.png", @"toppipestylefour.png", @"toppipestylefive.png", nil];

然后使用:

在该数组的随机索引处使用图像名称创建和设置图像
imageView.image = [UIImage imageNamed:[imageNameArray objectAtIndex:arc4random_uniform((uint32_t)[imageNameArray count])];
相关问题