Search code examples
iosxcodemaskcashapelayer

CAShapeLayer mask view


I have one problem. I look for the answers on the net and I don't understand why is not working. I must do some stupid mistake which I can't figure it out.

if I make :

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(10, 10, 300, 400)];
    view.backgroundColor = [UIColor blueColor];
    [self.view addSubview:view];

}

it create blue view on the screen, but if I make

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(10, 10, 300, 400)];
    view.backgroundColor = [UIColor blueColor];
    [self.view addSubview:view];

    CAShapeLayer * layer = [[CAShapeLayer alloc]init];
    layer.frame = CGRectMake(10, 10, 30, 30);
    layer.fillColor = [[UIColor blackColor] CGColor];

    view.layer.mask = layer;

}

it don't show anything.

If I understand correctly it should mask at (10,10,30,30)?


Solution

  • You need to set the path on the CAShapeLayer:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
    
        UIView * view = [[UIView alloc]initWithFrame:CGRectMake(10, 10, 300, 400)];
        view.backgroundColor = [UIColor blueColor];
        [self.view addSubview:view];
    
        CAShapeLayer * layer = [[CAShapeLayer alloc]init];
        layer.frame = view.bounds;
        layer.fillColor = [[UIColor blackColor] CGColor];
    
        layer.path = CGPathCreateWithRect(CGRectMake(10, 10, 30, 30), NULL);
    
        view.layer.mask = layer;
    }