Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shadow not appearing for UIView using CALayer

I have a subclassed UIView loaded from a nib, and I cannot get a shadow to draw around it. I'm trying to get a shadow to appear around the entire view for quite some time now. I elected to place it in it's own sublayer to simplify animating it later. Here's the code:

-(void)awakeFromNib 
{
    self.clipsToBounds = NO;

    // set up the shadow layer
    CALayer *shadow = [CALayer layer];
    shadow.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.bounds.size.width, self.bounds.size.height);
    shadow.shadowColor = [UIColor blueColor].CGColor;
    shadow.shadowRadius = 15.0;
    shadow.opacity = 1.0;
    [self.layer addSublayer:shadow];
    // I set this property so I have access to it later to more easily animate it.
    self.shadowLayer = shadow;
}

When I NSLog the shadowLayer property, the coordinates and frame are correct. It's matches the view it's backing.

I also set a border color and corner radius on self.layer and it appears correctly. If I put the shadow on self.layer it appears but it encompasses all the subviews of my parent UIView.

Any help is greatly appreciated.

like image 857
David Nix Avatar asked Nov 08 '11 02:11

David Nix


People also ask

What is shadow offset?

shadowOffset : the offset of the layer's shadow. The type of this property is CGSize. Width controls the shadow's horizontal offset, and the height controls its vertical offset. The default value of this property is (0.0, -3.0) .

How shadow offset works Swift?

ShadowOffset does what its name suggests, it offsets the shadow based on the input. For example, if you have a shadow radius of 10 and have an offset of (5, 5), the shadow will have a width of 5 on top/left and 15 on bottom/right.


1 Answers

Am assuming you have QuartzCore imported. I think you need to set & create a border to the UIView. The way to use this [self roundedLayerWithShadow:yourView.layer radius:5.0f];

- (void)roundedLayerWithShadow:(CALayer *)viewLayer 
                        radius:(float)r 
{
    [viewLayer setMasksToBounds:YES];
    [viewLayer setCornerRadius:r];        
    [viewLayer setBorderColor:[RGB(180, 180, 180) CGColor]];
    [viewLayer setBorderWidth:1.0f];

    [viewLayer setShadowColor:[RGB(0, 0, 0) CGColor]];
    [viewLayer setShadowOffset:CGSizeMake(0, 0)];
    [viewLayer setShadowOpacity:1];
    [viewLayer setShadowRadius:2.0];
    return;
}
like image 99
Srikar Appalaraju Avatar answered Oct 22 '22 08:10

Srikar Appalaraju