I'm trying to draw a custom-shaped shadow using CALayer
:
#import <QuartzCore/QuartzCore.h>
@implementation ZKSBAppDelegate
@synthesize window = _window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSView *view = self.window.contentView;
view.wantsLayer = YES;
CALayer *shadowLayer = [CALayer layer];
shadowLayer.shadowOpacity = 1;
shadowLayer.shadowRadius = 1;
shadowLayer.shadowOffset = NSMakeSize(0, 0);
CGMutablePathRef shadowPath = CGPathCreateMutable();
// setting the following rect's width to 100 fixes everything.
// setting it to 130 screws the shadow even more.
CGPathAddRect(shadowPath, NULL, CGRectMake(4, 0, 120, 48));
CGPathAddRect(shadowPath, NULL, CGRectMake(120, 50, 116, 48));
shadowLayer.shadowPath = shadowPath;
CGPathRelease(shadowPath);
[view.layer addSublayer:shadowLayer];
}
@end
You can create an empty Cocoa project in Xcode, replace your app.delegate's .m file content with the above code and try it yourself.
It looks like specific shadow path geometry causes CALayer
to go nuts.
For example:
CGPathAddRect(shadowPath, NULL, CGRectMake(4, 0, 100, 48));
CGPathAddRect(shadowPath, NULL, CGRectMake(120, 50, 116, 48));
This one looks perfectly okay:
Now I'm going to make the 1st rectangle wider by 20 points:
CGPathAddRect(shadowPath, NULL, CGRectMake(4, 0, 120, 48));
CGPathAddRect(shadowPath, NULL, CGRectMake(120, 50, 116, 48));
...doesn't look so good anymore. Plus 10 points:
CGPathAddRect(shadowPath, NULL, CGRectMake(4, 0, 130, 48));
CGPathAddRect(shadowPath, NULL, CGRectMake(120, 50, 116, 48));
Now that is plain wrong, isn't it?
So, the question is: what the hell is going on, am I doing it wrong or something? Do you think it's a bug and I should file a report?
shadowPath controls the shape of the shadow. This defaults to nil , which causes UIKit to render the view offscreen to figure out the shadow shape. shadowRadius controls how blurred the shadow is. This defaults to 3 points.
shadowOffset = CGSizeMake(2.0, 2.0)]; This will set the shadow to appear to the bottom right. The Offset value can be anything you want, the first value in the CGSize is distance left/right (with negative being left, and positive being right), and second value is distance up/down (negative/positive respectively).
Yes, that sounds like a bug. Even if it's not, by filing a bug report Apple should respond and give you useful information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With