在UIView上随机放置UIImageViews而不重叠

时间:2012-12-28 17:57:32

标签: objective-c ios uiview uiimageview

我正在做的是在视图上随机放置UIImageViews,我正在做的那部分工作就是这样:

return (int)0 + arc4random() % (self.view.bounds.frame.size.height-0+1);

也是宽度。

我遇到的是一些UIImageViews相互重叠。我知道我可以使用CGRectIntersectsRect但是我怎么能循环使用它,直到所有UIImageViews不相互重叠?

1 个答案:

答案 0 :(得分:3)

以下是您可以修改当前方法以放置图像视图的示例,如我之前的评论中所述:

// make sure this array is a member object, else pass it to the makeFrame method below.
NSArray *imageviews = [[NSArray alloc] initWithObjects: view1, view2, view3, nil]; // make sure they have tags! set the .tag property of each imageview in the array.
UIView *mainView = nil; // this won't really be nil - this is the view you are adding your imageviews to.

for (int i = 0; i < [imageviews count]; i++)
{
    UIImageView *imageview = [imageviews objectAtIndex: i];
    CGRect newFrame = [self makeFrameForView: imageview];

    while (newFrame.origin.x == 0 && newFrame.origin.y == 0)
    {
        // then the method returned CGRectZero. create it again until we get a good frame.
        newFrame = [self makeFrameForView: imageview];
    }

    [imageview setFrame: newFrame];
}


-(CGRect)makeFrameForView: (UIImageView*)theImageView
{
    CGRect newFrame = nil; // create your new frame here using arc4random etc and the parameters you prefer.

    for (int i = 0; i < [imageviews count]; i++)
    {
        UIImageView *imageview = [imageviews objectAtIndex: i];

        // first, ensure you aren't checking the same view against itself!
        if (theImageView.tag != imageview.tag)
        {
            BOOL intersectsRect = CGRectIntersectsRect(imageview.frame, newFrame);

            if (intersectsRect)
                return CGRectZero; // throw an "error" rect we can act upon.

        }
    }

    return newFrame;
}