在iphone的其他imageview中限制imageView的位置

时间:2011-11-02 15:18:16

标签: iphone cocoa-touch imageview

我有2个图像视图,即mainImageView& smallImageView。我的smallImageView作为子视图添加到mainImageView中。我的smallImageView是可拖动的(即在视图中移动)。我想在mainImageView中限制smallImageView的移动(我的smallImageView不应该在mainImageView之外)。我的smallImageView包含圆圈作为图像。这是我的代码

 -(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];
    }


}

我该如何解决这个问题。感谢。

1 个答案:

答案 0 :(得分:2)

在两种触控方式中,

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

这种方法的缺点是即使您的触摸没有在小视图上开始,小视图也会移动到您触摸的任何位置。

如果你想避免这种情况,只有当你的touchesBegan在小视图中开始时才设置'拖动'布尔状态,并且只有在拖动布尔值为YES时才响应touchesMoved。在touchesEnded上设置拖动到NO。

编辑:主视图是一个圆圈。

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;
}