具体实现的套路有两种
1、在图层下方在添加一个背景图层, 分别设置。
self.layerView1.layer.cornerRadius =20.0f;self.layerView2.layer.cornerRadius =20.0f;//add a border to our layersself.layerView1.layer.borderWidth =5.0f;self.layerView2.layer.borderWidth =5.0f;//add a shadow to layerView1self.layerView1.layer.shadowOpacity =0.5f;self.layerView1.layer.shadowOffset =CGSizeMake(0.0f,5.0f);self.layerView1.layer.shadowRadius =5.0f;//add same shadow to shadowView (not layerView2)self.shadowView.layer.shadowOpacity =0.5f;self.shadowView.layer.shadowOffset =CGSizeMake(0.0f,5.0f);self.shadowView.layer.shadowRadius =5.0f;//enable clipping on the second layerself.layerView2.layer.masksToBounds =YES;
2、通过layer的shadowPath设置
@interfaceViewController()@property(nonatomic,weak)IBOutletUIView*layerView1;@property(nonatomic,weak)IBOutletUIView*layerView2;@end@implementationViewController- (void)viewDidLoad{ [superviewDidLoad];//enable layer shadowsself.layerView1.layer.shadowOpacity =0.5f;self.layerView2.layer.shadowOpacity =0.5f;//create a square shadowCGMutablePathRefsquarePath =CGPathCreateMutable();CGPathAddRect(squarePath,NULL,self.layerView1.bounds);self.layerView1.layer.shadowPath = squarePath;CGPathRelease(squarePath); //create a circular shadowCGMutablePathRefcirclePath =CGPathCreateMutable();CGPathAddEllipseInRect(circlePath,NULL,self.layerView2.bounds);self.layerView2.layer.shadowPath = circlePath;CGPathRelease(circlePath);}@end
如果是一个矩形或者是圆,用CGPath会相当简单明了。但是如果是更加复杂一点的图形,UIBezierPath这个类会更加合适。