Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add shadow around the masked region of a CALayer

I'm masking a CAGradientLayer with a CAShapeLayer in order to generate a bookmark that sits inside certain rows in my table.

enter image description here

        CGMutablePathRef path = CGPathCreateMutable();
        CGPathAddLines(path,
                       NULL,
                       (CGPoint[]){
                           CGPointMake(8, 0),
                           CGPointMake(22, 0),
                           CGPointMake(22, 22),
                           CGPointMake(15, 16),
                           CGPointMake(8, 22)
                       },
                       5);
        CGPathCloseSubpath(path);

        CAShapeLayer *mask = [CAShapeLayer layer];
        mask.fillColor = [UIColor redColor].CGColor;
        mask.bounds = CGRectMake(0, 0, 30, 30);
        mask.path = path;
        mask.anchorPoint = CGPointMake(0, 0);

        CGPathRelease(path);

        CAGradientLayer *favoriteBadge = [CAGradientLayer layer];
        favoriteBadge.colors =
            @[(id)[UIColor colorWithRed:.97f green:0.5f blue:0.1f alpha:1.f].CGColor, // orange
              (id)[UIColor colorWithRed:1.f green:.8f blue:0.f alpha:1.f].CGColor]; // yellow
        favoriteBadge.locations = @[@0.0, @1.0];
        favoriteBadge.bounds = CGRectMake(0, 0, 30, 30);
        favoriteBadge.anchorPoint = CGPointMake(1, 0);
        favoriteBadge.position = CGPointMake(self.bounds.size.width, 0);
        favoriteBadge.mask = mask;
        // FIXME: This shadow is not being applied
        favoriteBadge.shadowColor = [UIColor colorWithRed:.97f green:0.5f blue:0.1f alpha:1.f].CGColor;
        favoriteBadge.shadowOpacity = 1.f;

This looks too flat, so I want to finish this off with a shadow around the shape itself. I've tried enabling shadow on the layer, but it doesn't seem to get applied. I assume it's being applied in the area that is not inside the shape. How can I add a shadow to the shape itself?

I could copy the layer, darken it and offset its position by a few pixels, but that feels wasteful when CoreAnimation can probably do it more efficiently for me.

like image 431
d11wtq Avatar asked Feb 03 '13 10:02

d11wtq


1 Answers

Create a container layer for your masked layer and apply the shadow to the container layer. I believe it's described here:

http://travisjeffery.com/b/2012/08/ios-how-to-mask-and-shadow-an-image/

like image 145
occulus Avatar answered Sep 22 '22 01:09

occulus