How to get the intersection of two CGPath?

I use CAShapeLayer.path and CALayer.mask to configure the image mask, I can achieve the “difference” and “merge” CGPath for CGPath by setting

 maskLayer.fillRule = kCAFillRuleEvenOdd/kCAFillRuleZero 

However, how can I get the intersection of two paths? I can't achieve this with the odd rule

Here is an example: enter image description here

 let view = UIImageView(frame: CGRectMake(0, 0, 400, 400)) view.image = UIImage(named: "scene.jpg") let maskLayer = CAShapeLayer() let maskPath = CGPathCreateMutable() CGPathAddEllipseInRect(maskPath, nil, CGRectOffset(CGRectInset(view.bounds, 50, 50), 50, 0)) CGPathAddEllipseInRect(maskPath, nil, CGRectOffset(CGRectInset(view.bounds, 50, 50), -50, 0)) maskLayer.path = maskPath maskLayer.fillRule = kCAFillRuleEvenOdd maskLayer.path = maskPath view.layer.mask = maskLayer 

How can I get the middle part of this image? I mean only the middle part (which is empty in the sample view).

I can do this easily in vector design software such as AI, so I think there should be a way to handle it.

+6
source share
1 answer
 extension UIImage { func doubleCircleMask(#circleSize:CGFloat)-> UIImage { let rectangle = CGRectMake(0, 0, size.width, size.height) UIGraphicsBeginImageContext(size) let x = size.width/2-circleSize/2 let y = size.height/2-circleSize/2 let offset = circleSize/4 let shape1 = UIBezierPath(roundedRect: CGRectMake(x-offset, y, circleSize, circleSize), cornerRadius: circleSize/2) shape1.appendPath(UIBezierPath(roundedRect: CGRectMake(x+offset, y, circleSize, circleSize), cornerRadius: circleSize/2)) shape1.addClip() drawInRect(rectangle) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } func doubleCircleIntersectionMask(#circleSize:CGFloat)-> UIImage { let rectangle = CGRectMake(0, 0, size.width, size.height) UIGraphicsBeginImageContext(size) let x = size.width/2-circleSize/2 let y = size.height/2-circleSize/2 let offset = circleSize/4 let shape1 = UIBezierPath(roundedRect: CGRectMake(x-offset, y, circleSize, circleSize), cornerRadius: circleSize/2) let shape2 = UIBezierPath(roundedRect: CGRectMake(x+offset, y, circleSize, circleSize), cornerRadius: circleSize/2) shape1.addClip() shape2.addClip() drawInRect(rectangle) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } } 

Testing

 let myPicture = UIImage(data: NSData(contentsOfURL: NSURL(string: "http://i.stack.imgur.com/Xs4RX.jpg")!)!)! let myPictureUnion = myPicture.doubleCircleMask(circleSize: 300) let myPictureIntersection = myPicture.doubleCircleIntersectionMask(circleSize: 300) 

enter image description here

+7
source

Source: https://habr.com/ru/post/985689/


All Articles