iOSAppDev
iOSAppDev

Reputation: 2783

Restrict position of imageView within other imageview in iphone

I have 2 image views namely mainImageView & smallImageView. My smallImageView is added as subview to mainImageView. My smallImageView is draggable (i.e moving around the view). I want to restrict the movement of smallImageView within mainImageView (my smallImageView should not go outside of mainImageView).My smallImageView contains circle as image. Here is my code

 -(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:touch.view];

    smallImageView.center = location;

}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:touch.view];


    if (location.x < mainImageView.frame.origin.x || location.y < mainImageView.frame.origin.y) {
        [self touchesBegan:touches withEvent:event];
    }


}

How can I fixed this problem. Thanks.

Upvotes: 1

Views: 154

Answers (1)

Jacob Jennings
Jacob Jennings

Reputation: 2836

In both touch methods,

UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:touch.view];
if(CGRectContainsPoint(mainImageView.frame, location)) {
    smallImageView.center = location;
}

The disadvantage to this approach is that the small view moves to wherever you touch even if your touch doesn't start on the small view.

If you want to avoid this, set a 'dragging' boolean state only if your touchesBegan starts in the small view, and only respond to the touchesMoved if the dragging boolean is YES. Set dragging to NO on touchesEnded.

EDIT: Main view is a circle.

UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:touch.view];

CGFloat xdifference = mainImageView.center.x - location.x;
CGFloat ydifference = mainImageView.center.y - location.y;
CGFloat distance = sqrt(xdifference * xdifference + ydifference * ydifference);
CGFloat radius = mainImageView.frame.size.width / 2;
if(distance < radius) {
    smallImageView.center = location;
}

Upvotes: 2

Related Questions