开发者

Drag an UIImageView in a restricted range

How is it possible to drag a UIImageView but only within a certain area of the screen? My code currently looks like this:

- (void) touchesMoved:(NSSet *)touches withEve开发者_如何转开发nt:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];
    touch.view.frame = CGRectMake(104, 171, 113, 49);

    if([touch view] == toggle)
    {

        CGPoint location = [touch locationInView:self.view];
        CGPoint newLocation = CGPointMake(toggle.center.x, location.y);

        toggle.center = newLocation;
        NSLog(@"%f \n",toggle.center.y);

    }  
}

I want to be able to drag the image only within the frame i have defined.


You can use CGRectContainsRect(rect1, rect2) to check if the first rect is completely inside of the second

bool CGRectContainsRect (
   CGRect rect1,
   CGRect rect2
);

When you are using UIViews and want to see if one view falls completely within the frame of a second, a related function CGRectContainsRect will do the checking for you. This does not check for an intersection; the union of both rectangles must be equal to the first rectangle for this to return true. The function takes two arguments. The first rectangle is always the surrounding item. The second argument either falls fully inside the first or it does not.

So your code could be something like this

CGPoint location = [touch locationInView:self.view];
CGPoint newLocation = CGPointMake(toggle.center.x, location.y);

CGRect r = CGRectMake(newLocation.x-self.frame.size.width/2, 
                      newLocation.y-self.frame.size.height/2, 
                      self.frame.size.width,
                      self.frame.size.height);
if(CGRectContainsRect(r, theOtherRect)){
    toggle.center = newLocation;
    NSLog(@"%f \n",toggle.center.y);
}

Other useful CoreGraphics functions: http://blogs.oreilly.com/iphone/2008/12/useful-core-graphics-functions.html

Another hint:NSLog(@"%@", NSStringFromCGPoint(toggle.center)) makes logging of CGTypes easier. use equivalently: NSStringFromCGRect(rect)


if (newLocation.y > NSMaxY(touch.view.frame)) newLocation.y = NSMaxY(touch.view.frame);
if (newLocation.y < NSMinY(touch.view.frame)) newLocation.y = NSMinY(touch.view.frame);
toggle.center = newLocation;

You can do the same for the x coordinate if you like.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜