【问题标题】:Random image display using rand()使用 rand() 随机显示图像
【发布时间】:2010-02-02 02:49:06
【问题描述】:

我只是在摆弄小应用程序,尝试学习 SDK 和 ObjC 2。

我正在尝试随机显示图片,但我一直在寻找不同的方法来显示图片。我已将图片上传到 SDKs 资源文件夹中。

无论如何,这是我的代码。有人可以引导我朝着正确的方向前进吗?

#import "randomViewController.h"

@implementation randomViewController


//not sure if this is the right way to do it really.
NSArray *comImage = [NSArray arrayWithObjects:
      [UIImage imageNamed:@"rock.png"],
      [UIImage imageNamed:@"paper.png"],
      [UIImage imageNamed:@"scissors.png"],
      nil];


- (IBAction) randButton {
 int text = rand() % 3;
 switch (text) {
  case 0:
   textView.text = @"Rock";
   break;
  case 1:
   textView.text = @"Paper";
   break;
  case 2:
   textView.text = @"Scissors";
   break;
  default:
   break;
 }
}

【问题讨论】:

  • 我不明白“我一直在寻找不同的方式来显示图片”这句话。并请格式化代码。谢谢。
  • 我不知道如何格式化代码,所以我把它放进去,对不起。基本上我所说的是我看到人们这样做的方式不同,我无法理解。谢谢:)

标签: iphone uiimage random


【解决方案1】:

我会这样做:

NSArray *myImageNames = [NSArray arrayWithObjects:@"rock.png", @"paper.png", @"scissors.png", nil];
int index = arc4random() % [myImageNames count];

UIImage *myImage = [UIImage imageNamed:[myImageNames objectAtIndex:index]];
myUIImageView.image = myImage;

显然,您可以保留 myImageNames,这样您就不必在每次运行时都重新创建它,如果您认为值得。

编辑:
知道了。请参阅更新的代码。它假定您已经在视图中添加了一个名为 myUIImageView 的 UIImageView。如果您的屏幕上已经有一个 UIButton,我假设您知道如何执行此操作。

添加 UIImageView:

在标题中声明 UIImageView *myUIImageView。
假设您使用 xib,请将其放在您的 viewDidLoad 中:

myUIImageView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
[self.view addSubview:myUIImageView];

用适当的值替换 x、y、宽度和高度。他们将确定 UIImageView 出现在视图中的哪个位置以及它有多大。

【讨论】:

  • 那么,我是否将“blah, foo, bar”替换为“rock.png”等图像名称?我把它全部放在 -(IBAction) 中吗?
  • 是的,是的。不过,您在做什么有点不清楚,因为您从未在上面的代码中使用过您的图像。
  • 基本上我想要做的是当我按下“按钮”时显示一张随机图片。它作为石头剪刀布的计算机选择。我只是不知道该怎么做,我认为这将是最好的方法。我刚刚开始学习它。
  • 你会认为我知道该怎么做,但看起来可能会骗人哈哈。我只是在学习不同类和方法之间的关系。感受一下这一切。感谢所有的帮助。
【解决方案2】:

要显示图像,您需要添加一个UIImageView 并将其image 属性设置为您想要的任何UIImage。查看 David 的回答,了解如何使用 objectAtIndex: 获取随机图像,然后将图像视图的 image 属性设置为该属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多