Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

objective c - Crop a CAShapeLayer retrieving the external path

I am trying to crop a layer with other, but, instead of creating a mask (B) and crop the layer (A) getting a cropped layer A with the shape of B, I want to get a layer with shape A and a 'hole' created by cropping with layer B.

*************               ***Layer A***
*  Layer A  *               *************
*   *****   *               ****    *****
*   * B *   *      ->       ****    ***** Layer A without shape B
*   *****   *               ****    *****
*           *               *************
*************               *************

How can I get the cropped layer A?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to create a mask that covers the area that you want to keep. This can be done by using an even-odd fill rule and create a path for a shape layer with both rectangles. You can create the shape like this (where the two rectangles would be your two frames). Then you set this as the mask to get the result that you are after.

CAShapeLayer *maskWithHole = [CAShapeLayer layer];

// Both frames are defined in the same coordinate system
CGRect biggerRect = CGRectMake(30, 50, 120, 200);
CGRect smallerRect = CGRectMake(80, 100, 50, 80);

UIBezierPath *maskPath = [UIBezierPath bezierPath];
[maskPath moveToPoint:CGPointMake(CGRectGetMinX(biggerRect), CGRectGetMinY(biggerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMinX(biggerRect), CGRectGetMaxY(biggerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMaxX(biggerRect), CGRectGetMaxY(biggerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMaxX(biggerRect), CGRectGetMinY(biggerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMinX(biggerRect), CGRectGetMinY(biggerRect))];

[maskPath moveToPoint:CGPointMake(CGRectGetMinX(smallerRect), CGRectGetMinY(smallerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMinX(smallerRect), CGRectGetMaxY(smallerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMaxX(smallerRect), CGRectGetMaxY(smallerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMaxX(smallerRect), CGRectGetMinY(smallerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMinX(smallerRect), CGRectGetMinY(smallerRect))];

[maskWithHole setPath:[maskPath CGPath]];
[maskWithHole setFillRule:kCAFillRuleEvenOdd];
[maskWithHole setFillColor:[[UIColor orangeColor] CGColor]];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...