天天看点

CALayer - 3

前面稍稍介绍了一些CALayer的显示上的属性,这里总结几个实用的使用例子:

自定义UIView的时候设置底层的layer:

@implementation ContainerView

- (instancetype)initWithFrame:(CGRect)frame
{
    if(!(self = [super initWithFrame:frame]))
    {
        return nil;
    }
    
    CALayer *styleLayer = [[CALayer alloc] init];
    styleLayer.cornerRadius = 4;
    styleLayer.shadowColor= [[UIColor blackColor] CGColor];
    styleLayer.shadowOffset = CGSizeMake(0, 0);
    styleLayer.shadowOpacity = 0.5;
    styleLayer.borderWidth = 1;
    styleLayer.borderColor = [[UIColor whiteColor] CGColor];

    //将图层缩小显示
    styleLayer.frame = CGRectInset(self.bounds, 12, 12);
    [self.layer addSublayer:styleLayer];

    //用于释放内存
    self.styleLayer = styleLayer;

    return self;
}

@end
           

CALayer的层树类似于UIView的视图树,你可以访问子层和父层:

//访问子层
    NSLog(@"star - %@", self.view.layer.sublayers);
    
    CALayer *layer=[CALayer layer];
    
    layer.backgroundColor=[UIColor brownColor].CGColor;
    layer.bounds=CGRectMake(0, 0, 200, 200);
    layer.position=CGPointMake(100, 100);
    
    [self.view.layer addSublayer:layer];
    
    NSLog(@"end - %@",self.view.layer.sublayers);
    
    NSLog(@"First one : %@", self.view.layer.sublayers[0]);
    
    //访问父层
    NSLog(@"SuperLayer is : %@", layer.superlayer);
           

后面会介绍一些作为动画效果的CALayer使用,期待!