문제

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 shadow 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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top