视图添加阴影的常见问题解析

2017-12-31  本文已影响0人  随风Wayne

如何给视图(UIView)添加阴影,相信大家都已经轻车熟路;参考代码如下:

contentView.layer.shadowColor = [UIColor redColor].CGColor; //颜色
contentView.layer.shadowRadius = 4.0f; //半径
contentView.layer.shadowOffset = CGSizeMake(3, 3); //偏移
contentView.layer.shadowOpacity = 1.0f; //透明度
常见问题
  1. 阴影不可见

    • 检查layer的masksToBounds属性是否为YES;
    • 检查阴影所属UIView的clipsToBounds属性是否为YES;

    原因: 视图外阴影的显示,需要超出视图本身区域;所以检测以上属性是否设置正确

  2. 子视图显示阴影


    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通道来决定阴影的路径;当父视图背景色有透明度,则所有的子视图也会阴影效果

总结: 推荐用法
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;

参考资料:

欢迎补充阴影的常见问题

上一篇 下一篇

猜你喜欢

热点阅读