陰影其實(shí)就是在視圖之外添加了一層類似遮罩的圖層 所以只要是設(shè)置了layer.masksToBounds的視圖都是無法直接顯示陰影的 需要另外添加一層視圖才開可以顯示 效果如下
下面來講實(shí)現(xiàn)
第一步 添加兩個(gè)視圖 一個(gè)需要設(shè)置圓角的視圖(以下用headBtn稱呼)一個(gè)用于添加陰影的視圖(以下用headBtnShadowView稱呼)
注意
- headBtnShadowView最好是與headBtn寬高相同 并且顏色設(shè)為clearColor
- headBtn是作為子視圖添加到headBtnShadowView上的
- 只在headBtn上進(jìn)行圓角相關(guān)設(shè)置
- 千萬不要設(shè)置 headBtnShadowView的layer.masksToBounds
第二步 設(shè)置陰影
- (void)setHeadBtnShadow{
_headBtnShadowView.layer.shadowOpacity = 0.6;//0-1 0就完全看不見越接近1陰影越實(shí)
_headBtnShadowView.layer.shadowColor = COLORMAINBLUE.CGColor;//陰影顏色
_headBtnShadowView.layer.shadowOffset = CGSizeMake(0, 3);
//偏移量 寬度表示橫坐標(biāo)偏移量 高度表示縱坐標(biāo)偏移量 這里是橫坐標(biāo)不變 縱坐標(biāo)向下偏移3
_headBtnShadowView.layer.shadowRadius = 4;
//該數(shù)值越大陰影擴(kuò)散的越遠(yuǎn)
//畫出圓形陰影
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);
*/
//更復(fù)雜的圖形需要用UIBezierPath來畫
}