如何给视图(UIView)添加阴影,相信大家都已经轻车熟路;参考代码如下:
contentView.layer.shadowColor = [UIColor redColor].CGColor; //颜色
contentView.layer.shadowRadius = 4.0f; //半径
contentView.layer.shadowOffset = CGSizeMake(3, 3); //偏移
contentView.layer.shadowOpacity = 1.0f; //透明度
常见问题
-
阴影不可见
- 检查layer的
masksToBounds
属性是否为YES; - 检查阴影所属UIView的
clipsToBounds
属性是否为YES;
原因: 视图外阴影的显示,需要超出视图本身区域;所以检测以上属性是否设置正确
- 检查layer的
-
子视图显示阴影
ShadowInSubviews.png
- 检查阴影所属UIView是否没有设置背景色(即背景色为clear color)
- 检查阴影所属UIView的背景色alpha通道小于1
shadowPath: The default value of this property is nil, which causes the layer to use a standard shadow shape. If you specify a value for this property, the layer creates its shadow using the specified path instead of the layer’s composited alpha channel.
原因: 如果没有设置layer的shadowPath属性,阴影渲染会根据视图最终的alpha通道来决定阴影的路径;当父视图背景色有透明度,则所有的子视图也会阴影效果
- 提高性能
- 设置layer的shadowPath属性
原因: 显式设定阴影的路径,可以避免Core Animation's的Off-screen渲染;如果没有设置,则需要离屏渲染计算出阴影的路径;
总结: 推荐用法
contentView.layer.shadowColor = [UIColor redColor].CGColor; //颜色
contentView.layer.shadowRadius = 4.0f; //半径
contentView.layer.shadowOffset = CGSizeMake(3, 3); //偏移
contentView.layer.shadowOpacity = 1.0f; //透明度
contentView.layer.shadowPath = CGPathCreateWithRect(CGRectMake(0, 0, 100, 100), NULL); //路径
contentView.clipsToBounds = YES;
如果使用Autolayout,可以在layoutSubviews或者viewDidLayoutSubviews方法中设置设置shadowPath;
参考资料:
欢迎补充阴影的常见问题
网友评论