The Secret Life of a CALayer (Part 4): Setting Shadows (Xcode)

This is a very simple update to the previous project. I want this time to add shadows. We do this by amending the viewDidAppear: method from last time, as shown here:


-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    blueLayer = [[CALayer alloc] init];
    positionOne = CGRectMake(100, 100, 100, 100);
    blueLayer.frame = positionOne;
    blueLayer.backgroundColor = [UIColor blueColor].CGColor;
    blueLayer.name = @"One";
    blueLayer.contents = (id) [UIImage imageNamed:@"plane"].CGImage;
    
    [self.view.layer addSublayer:blueLayer];
    
    redLayer = [[CALayer alloc] init];
    positionTwo= CGRectMake(100, 400, 100, 100);
    redLayer.frame = positionTwo;
    redLayer.backgroundColor = [UIColor redColor].CGColor;
    redLayer.name=@"Two";
    
    [self.view.layer addSublayer:redLayer];
    
    yellowLayer = [[CALayer alloc] init];
    positionThree = CGRectMake(400, 100, 100, 100);
    yellowLayer.frame = positionThree;
    yellowLayer.backgroundColor = [UIColor yellowColor].CGColor;
    yellowLayer.name = @"Three";
    
    [self.view.layer addSublayer:yellowLayer];
    
    greenLayer = [[CALayer alloc] init];
    positionFourCGRectMake(400, 400, 100, 100);
    greenLayer.frame =positionFour;
    greenLayer.backgroundColor = [UIColor greenColor].CGColor;
    greenLayer.name=@"Four";
    
    [self.view.layer addSublayer:greenLayer];
    
    NSArray *subLevelLayers = [self.view.layer sublayers];
    
    for (CALayer *layerName in subLevelLayers) {
        [layerName setShadowColor:[UIColor blackColor].CGColor];
        [layerName setShadowOpacity:0.25];
        [layerName setShadowRadius:6.0];
        [layerName setShadowOffset:CGSizeMake( 8 , 8)];
    }
    
}


In order to add the shadow we create an NSArray of the sublayers and then cycle through them to set the shadow. For a more detailed and extensive look at CALayer shadows, I highly recommend this post over at designerd.

But if you're staying here, then why don't we go one step further and add a border and curved corners to the layers as well? Easily done, just add the following code to your new "for in" statement.


        layerName.cornerRadius = 5;
        layerName.borderWidth = 2;
        layerName.borderColor =[UIColor grayColor].CGColor;


The Secret Life of a CALayer: Part 1 | Part 2 | Part 3 | Part 4


Comments