阴影其实就是在视图之外添加了一层类似遮罩的图层 所以只要是设置了layer.masksToBounds的视图都是无法直接显示阴影的 需要另外添加一层视图才开可以显示 效果如下
下面来讲实现
第一步 添加两个视图 一个需要设置圆角的视图(以下用headBtn称呼)一个用于添加阴影的视图(以下用headBtnShadowView称呼)
注意
- headBtnShadowView最好是与headBtn宽高相同 并且颜色设为clearColor
- headBtn是作为子视图添加到headBtnShadowView上的
- 只在headBtn上进行圆角相关设置
- 千万不要设置 headBtnShadowView的layer.masksToBounds
第二步 设置阴影
- (void)setHeadBtnShadow{
_headBtnShadowView.layer.shadowOpacity = 0.6;//0-1 0就完全看不见越接近1阴影越实
_headBtnShadowView.layer.shadowColor = COLORMAINBLUE.CGColor;//阴影颜色
_headBtnShadowView.layer.shadowOffset = CGSizeMake(0, 3);
//偏移量 宽度表示横坐标偏移量 高度表示纵坐标偏移量 这里是横坐标不变 纵坐标向下偏移3
_headBtnShadowView.layer.shadowRadius = 4;
//该数值越大阴影扩散的越远
//画出圆形阴影
CGMutablePathRef circlePath = CGPathCreateMutable();
CGPathAddEllipseInRect(circlePath, NULL, self.headBtn.bounds);
self.headBtnShadowView.layer.shadowPath = circlePath;
CGPathRelease(circlePath);
/**
//画方形阴影
CGMutablePathRef squarePath = CGPathCreateMutable();
CGPathAddRect(squarePath, NULL, self.headBtn.bounds);
self.headBtnShadowView.layer.shadowPath = squarePath;
CGPathRelease(squarePath);
*/
//更复杂的图形需要用UIBezierPath来画
}
网友评论