How to keep an image from going out side of a set area

87 Views Asked by At

I'm trying to make it so when you touch the image it moves to a random spot, but I now realize I need it to stay with in a set space so I can add things like a score counter. The problem I'm having is that I have no idea how to do this so any help is appreciated.

My Code:

-(IBAction)hideImage {

CGFloat xRange = self.view.bounds.size.width - Image.bounds.size.width;
CGFloat yRange = self.view.bounds.size.height - Image.bounds.size.height;

CGFloat minX = self.view.center.x - (xRange / 2);
CGFloat minY = self.view.center.y - (yRange / 2);

int randomX = (arc4random() % (int)floorf(xRange)) + minX;
int randomY = (arc4random() % (int)floorf(yRange)) + minY;
Image.center = CGPointMake(randomX, randomY);

}

Thank you.

2

There are 2 best solutions below

0
Liftoff On

You could use a UIView that has the frame that you want. Then add the UIImageView to the UIView and set:

[thisView setClipsToBounds: YES];

So:

CGRect myBounds = CGRectMake(0, 0, 320, 300);
UIView* thisView = [[UIView alloc] initWithFrame: myBounds];
[self.view addSubview: thisView];

UIImageView* image = [[UIImageView alloc] initWithFrame:...];
//Other image code
[thisView addSubview: image];

[thisView setClipsToBounds: YES];
0
DaveIngle On

If you have a UIImageView property called movingImageView as a subview, try this:

-(IBAction)hideImage {
    UIView *containerView = self.view;
    UIView *movingView = self.movingImageView;
    CGFloat xRange = CGRectGetWidth(containerView.bounds) - CGRectGetWidth(movingImageView.bounds);
    CGFloat yRange = CGRectGetHeight(containerView.bounds) - CGRectGetHeight(movingImageView.bounds);

    CGFloat minX = CGRectGetMidX(movingImageView.bounds);
    CGFloat minY = CGRectGetMidY(movingImageView.bounds);

    NSInteger randomX = (arc4random() % (NSInteger)floorf(xRange)) + minX;
    NSInteger randomY = (arc4random() % (NSInteger)floorf(yRange)) + minY;
    self.movingImageView.center = CGPointMake(randomX, randomY);
}

When the imageView's bounds is greater or equal to the container's bounds things will break.

This is pretty much the same code as you already had, if the 'image' is actually contained in a UIButton, you could change the method declaration to be:

-(IBAction)hideImage:(id)sender {
   UIView *containerView = self.view;
   UIView *movingView = (UIView *)sender
   ... The rest is same as above ...