简体   繁体   English

UICollisionBehavior - UIView碰撞的自定义形状

[英]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. 我试图弄清楚如何使用UIKit Dynamics成功碰撞两个具有自定义边界形状的UIView。

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). 我也想这样做,但我不认为你可以在当前的UIKit Dynamics for iOS 7下做到这一点。添加到动画师的项目必须采用UIDynamicItem协议(UIView确实)。 The protocol only specifies their boundaries to be rectangular, via the bounds property, which is a CGRect. 协议仅通过bounds属性(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. 您可以修改Xcode中的DynamicsCatalog示例代码,以查看使用不移动的曲线边界。

Create a new view file called BumperView, subclass of UIView. 创建一个名为BumperView的新视图文件,UIView的子类。 In BumperView.m, use this drawRect: 在BumperView.m中,使用此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. 在“项目属性”页面的故事板中,在框下方的某处添加一个视图,并将其类更改为BumperView,并将其背景颜色更改为清除。 Create an outlet named bumper to it in APLItemPropertiesViewController.m, but give it class BumperView. 在APLItemPropertiesViewController.m中为它创建一个名为bumper的插座,但是给它类BumperView。 Add the following in the viewDidAppear function, after collisionBehavior has been created: 在创建了collisionBehavior之后,在viewDidAppear函数中添加以下内容:

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. 运行它并转到“项目属性”页面以查看椭圆形反弹的矩形。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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