Search code examples
iosobjective-ccocoa-touchcalayercashapelayer

cant add a shape layer into a view's layer


I'm working on CAShapeLayer by creating a layer using CAShapeLayer like following:

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.frame = CGRectMake(150, 50, 200, 200);
shapeLayer.fillColor = [UIColor whiteColor].CGColor;
shapeLayer.strokeColor = [UIColor orangeColor].CGColor;
[self.view.layer addSublayer:shapeLayer];

However, when I execute the codes and I cant see my shapeLayer in the simulator/device.
What I am missing here.

PS : If I am using CALayer *shapeLayer = [CALayer layer]; it works.Confused


Solution

  • add a path to it, like

     shapeLayer.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius) 
                                                  cornerRadius:radius].CGPath;
    

    A shaped layer needs a shape…


    I put this in my View Controller and it works fine:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.frame = CGRectMake(150, 50, 200, 200);
        shapeLayer.fillColor = [UIColor whiteColor].CGColor;
        shapeLayer.strokeColor = [UIColor orangeColor].CGColor;
    
        NSUInteger radius = 90;
        shapeLayer.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius)
                                                     cornerRadius:radius].CGPath;
        [self.view.layer addSublayer:shapeLayer];   
    }
    

    enter image description here

    If you change the path like

    shapeLayer.path = [UIBezierPath bezierPathWithRect:shapeLayer.bounds].CGPath;
    

    it'll result in

    enter image description here