简体   繁体   中英

UICollisionBehavior - custom shape for UIView collision

I'm trying to figure out how to use UIKit Dynamics to successfully collide two UIViews which have custom boundary shapes.

The most basic example I can think of to explain my question is to have two circles collide (taking in to account their round corners) instead of their square boundary.

I'm sure I've seen this somewhere but I can't find any documentation or discussion on the subject from any official source.

I'd like to do this too, but I don't think you can do it under the current UIKit Dynamics for iOS 7. Items added to the animator must adopt the UIDynamicItem protocol (UIView does). The protocol only specifies their boundaries to be rectangular, via the bounds property, which is a CGRect. There's no custom hit test.

However, you can add a fixed Bezier path to the collision set, and it could be circular or any shape you can make with a path, but it would act like a curved wall that other rectangular objects bounce off of. You can modify the DynamicsCatalog sample code in Xcode to see the use of a curved boundary which doesn't move.

Create a new view file called BumperView, subclass of UIView. In BumperView.m, use this drawRect:

#define LINE_WIDTH 2.0
- (void)drawRect:(CGRect)rect
{
    UIBezierPath *ovalPath = [UIBezierPath bezierPathWithOvalInRect:CGRectInset(self.bounds, LINE_WIDTH/2, LINE_WIDTH/2)];
    [[UIColor blueColor] setStroke];
    [[UIColor lightGrayColor] setFill];
    ovalPath.lineWidth = LINE_WIDTH;
    [ovalPath stroke];
    [ovalPath fill];
}

In the storyboard for the Item Properties page, add a View somewhere below the boxes and change its class to BumperView, and change its background color to clear. Create an outlet named bumper to it in APLItemPropertiesViewController.m, but give it class BumperView. Add the following in the viewDidAppear function, after collisionBehavior has been created:

UIBezierPath *bumperPath = [UIBezierPath bezierPathWithOvalInRect:self.bumper.frame];
[collisionBehavior addBoundaryWithIdentifier:@"Bumper" forPath:bumperPath];

Run it and go to the Item Properties page to see the rectangles bounce off the oval.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM