简体   繁体   中英

How do I cut a notch out of a CALayer?

I have a set of views in a carousel, each using a CAGradientLayer as a background. The carousel sits over a textured background. I've been asked for the background to poke up in a triangle to show the selected view. I can't just use a triangular image with the background texture, as it won't necessarily match up with the main background. I'd like to cut a notch out of the background of the current view, so that the textured background is visible through the notch.

How should I go about this? Is it possible to make a polygonal layer?

I found I was able to do it using a CAShapeLayer:

CAShapeLayer *mask = [[[CAShapeLayer alloc] init] autorelease];
mask.frame = backgroundLayer.bounds;
mask.fillColor = [[UIColor blackColor] CGColor];

CGFloat width = backgroundLayer.frame.size.width;
CGFloat height = backgroundLayer.frame.size.height;

CGMutablePathRef path = CGPathCreateMutable();

CGPathMoveToPoint(path, nil, 0, 0); 
CGPathAddLineToPoint(path, nil, width, 0);
CGPathAddLineToPoint(path, nil, width, height);
CGPathAddLineToPoint(path, nil, (width/2) + 5, height);
CGPathAddLineToPoint(path, nil, width/2, height - 5);
CGPathAddLineToPoint(path, nil, (width/2) - 5, height);
CGPathAddLineToPoint(path, nil, 0, height);
CGPathAddLineToPoint(path, nil, 0, 0);
CGPathCloseSubpath(path);

mask.path = path;
CGPathRelease(path);

backgroundLayer.mask = mask;

I don't think that we can draw polygonal layers. However, I believe that the expected result can be achieved using two different ways:-

  1. If your images are of the same size then you can use a PNG image with transparent notch in between (or outside as per your desire).

  2. Draw a filled rectangle and transparent triangular polygon. Then you need to intersect both the polygon (rectangle and triangle). The resulted Shape should be placed over the carousel image. The benefit of this method is that you can dynamically change the size and shapes of the polygons if required.

Hope this helps!

Is it possible to make a polygonal layer?

No.

How should I go about this?

Use a mask - a png image that's the same size as your layer but has a bit cut out - this will make the CALayer appear to have a chunk cut out of it. (However, it won't so if you cut-out is big, you might get users trying to touch whatever is behind it, which won't work!).

See the documentation (and search stackoverflow ) for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM