简体   繁体   中英

Collision bounding path origin in UIView iOS 9

I'm trying to setup the collison bounding path of a custom UIView. What I currently do is converting a SVG file to a path using PocketSVG and creating an UIBezierPath from it. Here's my code:

@implementation CustomView {

    UIBezierPath * _mask;
    CGPathRef _myPath;

}

- (UIDynamicItemCollisionBoundsType) collisionBoundsType {

    return UIDynamicItemCollisionBoundsTypePath;

}

- (UIBezierPath *) collisionBoundingPath {

    _myPath = [PocketSVG pathFromSVGFileNamed:@"line5"];

    _mask = [UIBezierPath bezierPathWithCGPath:_myPath];

    return _mask;

}

It works "correctly" but the UIBezierPath is drawn at the center of my view so this is what I get:

Left: Actual behavior ---> Right: Expected behavior

在此处输入图片说明

And since the collision bounds are invisible the collision seems to happen before touching the view visually (they are actually touching because of the origin of the collision bounds path).

According to Apple documentation regarding collisionBoundingPath :

The path object you create must represent a convex polygon with counter-clockwise or clockwise winding, and the path must not intersect itself. The (0, 0) point of the path must be located at the center point of the corresponding dynamic item. If the center point does not match the path's origin, collision behaviors may not work as expected.

So my main question is, since the (0,0) coordinates of the path must be at the center of my view, how can I achieve what I'm looking for? The perfect scenario would be if UIBezierPath start drawing at the origin of its UIView but since I'm adding a path from a SVG it is automatically draw from the center of the view.

You can use a transformation to move the CGPath into the appropriate position. For example:

- (UIBezierPath *) collisionBoundingPath {

    _myPath = [PocketSVG pathFromSVGFileNamed:@"line5"];

    CGAffineTransform translation = CGAffineTransformMakeTranslation(-self.bounds.size.width * 0.5,-self.bounds.size.height * 0.5);
    CGPathRef movedPath = CGPathCreateCopyByTransformingPath(_myPath,&translation);

    _mask = [UIBezierPath bezierPathWithCGPath:movedPath];

    return _mask;

}

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