0

よし、全部で 5 つのカスタム イメージがあります。各画像を設定する必要がある値は次のとおりです。

Image1 = 1
Image2 = 2
Image3 = 3
Image4 = 4
Image5 = 5

これらに値を割り当てる必要があるのは、値が 50 に達するまで xcode でビューにランダムに配置する必要があるためです。

int 値を UIImage に割り当てようとすると警告が表示されるため、これらの画像に値を割り当てるにはどうすればよいですか。また、オーバーラップせずにビューに画像をランダムに配置するには、どのような方法を使用しますか?

助けてくれてありがとう!

4

3 に答える 3

3

アプリはUIImageViewではなくUIImageをビューに配置します。すべてのUIViewサブクラスと同様UIImageViewにプロパティがありNSInteger tagますが、問題を正しく理解していれば、それも必要ないと思います。

// add count randomly selected images to random positions on self.view
// (assumes self is a kind of UIViewController)
- (void)placeRandomImages:(NSInteger)count {

    for (NSInteger i=0; i<count; ++i) {
        UIImage *image = [self randomImage];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        imageView.frame = [self randomFrameForImage:image];
        [self.view addSubview:imageView];

        // add a tag here, if you want, but I'm not sure what for
        // imageView.tag = i;
    }
}

// answer a random image from the app's bundle
// assumes the images are named image-x where x = 0..4
- (UIImage *)randomImage {

    NSInteger imageNumber = arc4random() % 5;
    NSString *imageName = [NSString stringWithFormat:@"image-%d", imageNumber];
    return [UIImage imageNamed:imageName];
}

// answer a random position for the passed image, keeping it inside the view bounds
- (CGRect)randomFrameForImage:(UIImage *)image {

    CGFloat imageWidth = image.width;
    CGFloat imageHeight = image.height;

    CGFloat maxX = CGRectGetMaxX(self.view.bounds) - imageWidth;
    CGFloat maxY = CGRectGetMaxY(self.view.bounds) - imageHeight;

    // random location, but always inside my view bounds
    CGFloat x = arc4random() % (NSInteger)maxX;
    CGFloat y = arc4random() % (NSInteger)maxY;

    return CGRectMake(x,y,imageWidth,imageHeight);
}
于 2013-10-07T22:54:06.343 に答える
0

画像を NSArray に入れ、次にNSHipsterから入れます:

NSArray からランダムな要素を選択する方法

空でない配列の範囲で乱数を生成するには、arc4random_uniform(3) を使用します。

if ([array count] > 0) {
  id obj = array[arc4random_uniform([array count])];
}
于 2013-10-07T23:03:51.827 に答える