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

标签 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。

我不确定执行此操作的最佳途径,我考虑过使用数组来执行此操作,但我不确定如何设置数组甚至随机调用图像。

最佳答案

您可以按照您的想法将图像名称放在一个数组中,例如。

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])];

关于ios - 每次重置时如何在 UIImageView 中显示随机图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23974425/

相关文章:

mysql - iOS 和 Mac OSX 与 MySQL 数据库通信

objective-c - iOS 滑动动画意外发生两次

ios - UIVisualEffectView:在 IB 中启用 Vibrancy 禁用模糊效果

ios - 如何在分页 UIScrollView 中显示确定的项目而不是仅从 0 加载它

ios - Objective C 如何读取嵌套的 JSON

ios - 从子级调用父 View 上的 PerformSegueWithIdentifier 不会更改 View

ios - 如何将 2 个 TableView 添加到单个 UIViewController 中?

iphone - 在导航 Controller 中按下后退按钮时是否可以不释放 View Controller ?

ios - 如何在 startWithGraphPath Facebook iOS 中标记好友

ios - 缩放 UIImage 以正确适应 UIImageView