In my experiments, I noticed that if you simply create a layer for a view and attempt to add a shadow, nothing appears.
Unless some color is applied to the border or the backgroundColor of the layer, no shadow will appear.
If clearColor is used for the background, then no shadow will appear.
Yet, if you add any pixel to it or a border, the shadow will appear.
I’m specifically applying a rectangular shadow to the layer through a bezier path.
Does anyone know what the minimum settings required on a layer for it to be able to display a shadow?
Assuming that you have a storyboard, and a UIView property on the screen called self.blueLayer, here’s some test Objective-C code that will render out a blue square layer with a shadow.
Changing the background color to clearColor or not applying a background color at all results in no shadow.
Is there a method to have a layer without any fill and a shadow?
Thanks in advance.
Alex Zavatone
@interface ViewController ()
@property (nonatomic, weak) IBOutlet UIView *layerView;
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UIColor *shadowColor;
CGFloat alpha;
CGFloat x;
CGFloat y;
CGFloat blur;
CGFloat spread;
shadowColor = [UIColor blackColor];
alpha = 0.8;
x = 0;
y = 8.0;
blur = 20.0;
spread = 20.0; // 1
//create sublayer
CALayer *blueLayer = [CALayer layer];
blueLayer.frame = CGRectMake(50.0f, 50.0f, 100.0f, 100.0f);
// blueLayer.frame = CGRectMake(0.0f, 0.0f, 250.0f, 128.0f);
blueLayer.backgroundColor = [UIColor blueColor].CGColor;
// blueLayer.backgroundColor = [UIColor clearColor].CGColor;
// blueLayer.borderWidth = 1;
// blueLayer.borderColor = [UIColor whiteColor].CGColor;
// Add Shadow to layer
//color = [UIColor greenColor];
blueLayer = [self addShadowToLayerAsRect: blueLayer
color: shadowColor
alpha: alpha
x: x
y: -y
blur: blur
spread: spread];
//add it to our view
[self.layerView.layer addSublayer:blueLayer];
}
- (CALayer *)addShadowToLayerAsRect:(CALayer *)layer
color:(UIColor *)color
alpha:(CGFloat)alpha
x:(CGFloat)x
y:(CGFloat)y
blur:(CGFloat)blur
spread:(CGFloat)spread
{
layer.masksToBounds = NO;
layer.shadowColor = color.CGColor;
layer.shadowOpacity = 1; // alpha;
layer.shadowOffset = CGSizeMake(x, y);
layer.shadowRadius = blur / 2 ; //UIScreen.mainScreen.scale;
if (spread == 0) {
layer.shadowPath = nil;
} else {
CGFloat deltaX = spread;
CGRect shadowRect = CGRectInset(layer.bounds, deltaX, deltaX);
layer.shadowPath = CFBridgingRetain([UIBezierPath bezierPathWithRect: shadowRect]);
}
return layer;
}