Search code examples
ioscalayercgpath

How to create a CGPath which exactly match a CALayer bounds when the layer rotate or scale?


We have a CALayer which shows image with edit information. Such as rotate, scale and translate. I want to make a CGPath which exactly match the layer bounds. When the layer rotate, my path should also rotate and its four corners should match the CALayer's four corners. The CGPath is actually used as a gray mask to show the clipped area of the image.

I try following code, but it does not work.

    f = self.imageLayer.frame;
    t = self.imageLayer.affineTransform;
    CGPathAddRect(path, &t, f);

The CALayer has its own CGAffineTransform. All edit information are applied via the CGAffineTransform.

Any hint will be appreciated, Thanks a lot.


Solution

  • If I got your question right you could be using UIBezierPath's usesEvenOddFillRule to cut around your image layer bounds dimming the rest of the visible screen. Basically you create a very large rectangular path (for some reasons CGRectInfinite doesn't work here) and cut out the area around your image layer. The trick is to use kCAFillRuleEvenOdd which flips what is considered inside and outside.

    Something like should work:

        let cutPath = UIBezierPath(roundedRect: imageLayer.bounds, cornerRadius: 0)
    
        let clipPath = UIBezierPath(rect: CGRectMake(-10e6, -10e6, 10e7, 10e7)) // CGRectInfinite isn't working here ?
        clipPath.appendPath(cutPath)
        clipPath.usesEvenOddFillRule = true
    
        let shape = CAShapeLayer()
        shape.contentsScale = UIScreen.mainScreen().scale
        shape.lineWidth = 2
        shape.fillColor = UIColor(red:0.1, green:0.1, blue:0.1, alpha:0.5).CGColor
        shape.fillRule = kCAFillRuleEvenOdd
        shape.strokeColor = UIColor.whiteColor().CGColor
    
        shape.path = clipPath.CGPath
        imageLayer.addSublayer(shape)
    
        // do a transformations here
        imageLayer.transform = CATransform3DMakeRotation(10.0, 1.0, 1.0, 0.8)
    

    Which results

    enter image description here