如何获得两个CGPath的交集?

时间:2015-04-22 14:31:12

标签: ios swift core-graphics core-animation

我正在使用CAShapeLayer.pathCALayer.mask设置图片掩码,我可以通过设置

CGPath实现“差异设置”和“联合”效果
maskLayer.fillRule = kCAFillRuleEvenOdd/kCAFillRuleZero

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

这是一个例子: 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

如何才能显示中间交叉区?

1 个答案:

答案 0 :(得分:7)

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
    }

}

<强>测试

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