Search code examples
core-animationcashapelayer

the strokeColor of CAShapeLayer not work


#import <UIKit/UIKit.h>

@interface UIView (Shape)

- (void)setShape:(CGPathRef)shape;

@end

#import "UIView+Shape.h"

@implementation UIView (Shape)
- (void)setShape:(CGPathRef)shape
{
    if (shape == nil) {
        self.layer.mask = nil;
    }

    CAShapeLayer* shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = shape;
    shapeLayer.fillColor = [[UIColor whiteColor] CGColor];
    shapeLayer.strokeColor = [[UIColor redColor] CGColor];
    shapeLayer.lineWidth = 0.5;
    self.layer.mask = shapeLayer;

}
@end

this is my code. i want to set the border color of the shape as red, but the border always clear color. i had to add a sublayer, as the code show bellow. and it work, why?

 - (void)setShape:(CGPathRef)shape strokeColor:(UIColor *)color
 {
    if (shape == nil) {
        self.layer.mask = nil;
    }

    CAShapeLayer* shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = shape;
//    shapeLayer.fillColor = [[UIColor whiteColor] CGColor];
//    shapeLayer.strokeColor = [[UIColor redColor] CGColor];
//    shapeLayer.lineWidth = 0.5;
    self.layer.mask = shapeLayer;

    CAShapeLayer *borderLayer = [CAShapeLayer layer];
    borderLayer.path = shape;
    borderLayer.lineWidth = 2;
    borderLayer.fillColor = [[UIColor clearColor] CGColor];
    borderLayer.strokeColor = [color CGColor];
    [self.layer addSublayer:borderLayer];
}

And sorry for my poor English.


Solution

  • You are adding your shape layer as a mask layer. That allows the brightness of the mask layer's pixels to determine the opacity of the layer it's masking. It sounds like that's not what you want.

    Instead, add your shape layer as a sublayer of your view's layer. Change

    self.layer.mask = shapeLayer;
    

    to

    [self.layer addSublayer: shapeLayer];
    

    That will cause your shape layer to drawn on top of your view's layer.