iOS开发中CALayer使用的基本教程

2020-01-14 17:52:10于丽

添加后

iOS开发中CALayer使用的基本教程

那是因为设置的image不是展示在主图层上的,而是显示在子图层上的。可以通过设置一个范围,设置超出主图层的部分把它给剪切掉。

有以下两种方法,建议使用layer中的方法(第二种)self.customView.layer.masksToBounds=YES;

复制代码
- (void)viewDidLoad
{
    [super viewDidLoad];
    //设置边框的宽度为20
    self.customView.layer.borderWidth=5;
    //设置边框的颜色
    self.customView.layer.borderColor=[UIColor blackColor].CGColor;
    
    //设置layer的圆角
    self.customView.layer.cornerRadius=20;
    //设置超过子图层的部分裁减掉
    //UI框架中使用的方法
//    self.customView.clipsToBounds=YES;
    self.customView.layer.masksToBounds=YES;
    
    //在view的图层上添加一个image,contents表示接受内容
    self.customView.layer.contents=(id)[UIImage imageNamed:@"me"].CGImage;
}

 

iOS开发中CALayer使用的基本教程

注意:layer中不能直接接受UI框架中的东西

4.设置阴影

  设置阴影,不光需要设置阴影颜色,还应该设置阴影的偏移位和透明度。

  因为如果不设置偏移位的话,那么阴影和layer完全重叠,且默认透明度为0(即完全透明)。

复制代码
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //设置阴影的颜色
    self.customView.layer.shadowColor=[UIColor blackColor].CGColor;