ios - 为什么masksToBounds = YES会阻止CALayer阴影?

通过以下代码段,我向我的 UIView 添加了阴影效果。效果很好。但只要我将 View 的 ma​​sksToBounds 属性设置为 YES。不再渲染阴影效果。

self.myView.layer.shadowColor = [[UIColor blackColor] CGColor];
self.myView.layer.shadowOpacity = 1.0;
self.myView.layer.shadowRadius = 10.0;
self.myView.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
self.myView.layer.cornerRadius = 5.0;
self.myView.layer.masksToBounds = YES; // <-- This is causing the Drop shadow to not be rendered
UIBezierPath *path = [UIBezierPath bezierPathWithCurvedShadowForRect:self.myView.bounds];
self.myView.layer.shadowPath = path.CGPath;
self.myView.layer.shouldRasterize = YES;

您对此有什么想法吗?

最佳答案

因为阴影是在 View 之外完成的效果,并且将 maskToBounds 设置为 YES 将告诉 UIView 不要绘制其外部的任何内容。

如果您想要一个带阴影的圆角 View ,我建议您使用 2 个 View :

UIView *view1 = [[UIView alloc] init];
UIView *view2 = [[UIView alloc] init];

view1.layer.cornerRadius = 5.0;
view1.layer.masksToBounds = YES;
view2.layer.cornerRadius = 5.0;
view2.layer.shadowColor = [[UIColor blackColor] CGColor];
view2.layer.shadowOpacity = 1.0;
view2.layer.shadowRadius = 10.0;
view2.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
[view2 addSubview:view1];
[view1 release];

https://stackoverflow.com/questions/3690972/

相关文章:

objective-c - .h 和 .m 文件中的@interface 定义之间的区别

objective-c - 标题中有两行文本的 UIButton (numberOfLines=2)

objective-c - 如何向 objc_exception_throw 添加断点?

iphone - NSTimeInterval 到 HH :mm:ss?

ios - 在自动布局中将 subview 的 X 居中抛出 "not prepared for t

objective-c - Objective-C中的ivars和属性有什么区别

objective-c - ARC : strong or retain? 的@property 定

iphone - 如何为 View 或图像沿弯曲路径的移动设置动画?

ios - 没有为应用商店上的应用程序找到有效的 'aps-environment' 权利字符串

iphone - 如何找到 malloc "double free"错误的原因?