2013-10-31 33 views
0

我有一个包含一组图像的数组。有一个循环从该数组中选取一个随机图像,然后在视图上随机显示图像。显示没有交集的图像

这是我正在使用的循环。它还有一些部分告诉它需要多长时间以及何时停止。因为我认为它是不相关的,所以我把它排除在外。

int randomImgNum = arc4random_uniform(5); 

UIImage *tempImg = [_imageArray objectAtIndex:randomImgNum]; 

UIImageView *tempImgView = [[UIImageView alloc] initWithImage:tempImg]; 

tempImgView.center = CGPointMake(arc4random() % 320,arc4random() % 480); 
[self.view addSubview:tempImgView]; 

我的问题是它会显示图像,但它们都是重叠的。我调整了所有这些图像的大小,以使它们全都适合屏幕而不必重叠。我不确定要放置什么代码来阻止它们相交。

我已经搜索了youtube,google,stackoverflow,并且只能真正找到人们询问如何让NSLog在拖动图像时告诉他们交叉点的位置。我无法找到解决方案令我疯狂!

任何和所有的建议表示赞赏!我事先感谢任何人的帮助!

+1

你是什么意思“重叠”?如果你能提供最终效果的图像,这使得这更清晰 – Jing

回答

0

不要在循环中重新创建UIImageView,只需全局分配一次并访问UIImageView的对象引用只分配immage。

如:

.h

UIImageView *imgView; 

.m

- (void)loadView { 

    imgView = [[UIImageView alloc] init]; 
    [self.view addSubview:imgView]; 
} 

在循环

int randomImgNum = arc4random_uniform(5); 

UIImage *tempImg = [_imageArray objectAtIndex:randomImgNum]; 

imgView.image = tempImg; 

imgView.center = CGPointMake(arc4random() % 320,arc4random() % 480); 
[self.view addSubview:imgView]; 

希望它会帮助你..

+0

所以当我添加你的代码时,它给了我这个:0x99810533:calll 0x99810538; szone_malloc_should_clear + 14.我不确定这意味着什么。它看起来像我所需要添加的是什么在.h和loadView是否正确?循环代码不会改变? – user2939895

+0

我编辑了我的答案检查现在.. – Venkat

+0

我不知道为什么这段代码不工作。它只是给了我相同的szone_malloc_should_clear + 14.这个错误是什么意思?我把代码放在我的.h中,把loadView放在我的viewDidLoad上面,然后改变我的循环如何放置它。我不知道还有什么要做 – user2939895

1

我调整了我所有的图像大小(100,100)然后在这个x是我的X点和y是我的Y点。在一行中,我显示两个图像没有任何重叠。最初我设置了x = 40;y = 70;。我按三个X位置40和140,我把每一行之间40分的差距图片..

NSArray *keys = [imageStore allKeys];//Imagestore is a dictionary which contain my images with key.. 


for (int i = 0; i < [imageStore count]; i++) 
     { 
      if (x == 40) 
      { 
       UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, 100, 100)]; 
       imageView.image = [imageStore objectForKey:[keys objectAtIndex:i]]; 
       [myScroller addSubview:imageView]; 
       x = x + 140; 
      } else{ 
       UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, 100, 100)]; 
       imageView.image = [imageStore objectForKey:[keys objectAtIndex:i]]; 
       [myScroller addSubview:imageView]; 
       x = 40; 
       y = y + imageView.frame.size.height + 40; 
      } 
     } 

我希望这将是对你有所帮助