在CALayer的蒙版区域周围添加阴影

时间:2013-02-03 10:43:16

标签: iphone core-animation

我正在使用CAGradientLayer屏蔽CAShapeLayer,以便生成位于我表格中某些行内的书签。

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;

这看起来太平了,所以我想用形状本身周围的阴影来完成这个。我已尝试在图层上启用阴影,但似乎没有应用。我认为它被应用在不在形状内的区域。如何在形状本身添加阴影?

我可以复制图层,使其变暗并将其位置偏移几个像素,但是当CoreAnimation可以为我更有效地执行此操作时,这会让您感到浪费。

2 个答案:

答案 0 :(得分:9)

为蒙版图层创建容器图层,并将阴影应用于容器图层。我相信这里描述的内容:

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

答案 1 :(得分:-2)

也许唯一错过的是

favoriteBadge.masksToBounds = NO