开发者

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.

  1. Capture the content of the shape layer into image
  2. Set the shadow to your liking
  3. Begin transparency layer
  4. Clip to the image of layers content - you'll be drawing outside of it
  5. 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜