How to make a CAShapeLayer throw a shadow in iPhone OS 3.0?
I'm using a CAShapeLayer with a path. Now I want it to throw a smooth shadow with about 10 units of thickness.
First: Yeah, I could create just 11 CAShapeLayer objects and each time increase the outline of the path by 1 unit with an different color and some more alpha on every iteration. But this way I blow up my memory footprint since the thing is half screen size and this would mean to have 11x a bitmap of half screen size in memory.
So since iPhone OS 3.2 I could probably use those nifty s开发者_如何学Pythonhadow properties on CALayer. But I want to stick to OS 3.0. So what options do I have, other than the nasty one above?
You could create the shadow using Core Graphics. The building blocks you'll need are described in QuartzDemo sample. In particular have a look at class QuartzMaskingView
in QuartzClipping.m.
- Capture the content of the shape layer into image
- Set the shadow to your liking
- Begin transparency layer
- Clip to the image of layers content - you'll be drawing outside of it
- Draw your image again
This results in shadow being painted outside of your masked area.
CGSize size = CGSizeMake(300, 100); UIGraphicsBeginImageContextWithOptions(size,NO, 0.0); [shapeLayer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); CGRect flippedImageRect = CGRectMake(0, 0, image.size.width, -image.size.height); CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextSaveGState(ctx); CGContextSetShadowWithColor(ctx, CGSizeMake(4, 4), 2, [[UIColor colorWithWhite:0 alpha:0.4] CGColor]); CGContextBeginTransparencyLayer(ctx, NULL); CGContextScaleCTM(ctx, 1.0, -1.0); CGContextClipToMask(ctx, flippedImageRect, [image CGImage]); CGContextSetFillColorWithColor(ctx, [[UIColor redColor] CGColor]); CGContextDrawImage(ctx, flippedImageRect, [image CGImage]); CGContextEndTransparencyLayer(ctx); CGContextRestoreGState(ctx);
精彩评论