如何获得两个CGPath的交集?

dua*_*uan 7 core-animation core-graphics ios swift

我正在使用CAShapeLayer.pathCALayer.mask设置图像蒙版,我可以CGPath通过设置实现"差异设置"和"联合"效果

maskLayer.fillRule = kCAFillRuleEvenOdd/kCAFillRuleZero
Run Code Online (Sandbox Code Playgroud)

但是,我怎样才能得到两条路径的交集?我甚至不能用奇怪的规则来实现它

这是一个例子: 在此输入图像描述

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
Run Code Online (Sandbox Code Playgroud)

我怎样才能显示中间交叉区域?

Leo*_*bus 8

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
    }

}
Run Code Online (Sandbox Code Playgroud)

测试

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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述