iosobjective-cuiviewcalayer

iOS Understanding Layer Masking


I am having some difficulty understanding on how layer masking works. Right now, I have a UIView with UILabels on it. I picture two layers - one with the UIView in the back and one for the labels on top. If I mask the UIView layer, the labels will be affected by the mask too.

The UILabels are children of the parent UIView, so I can understand a parent mask affecting the children as well.

However, when I look at it in terms of layers, it doesn't seem to make sense. Why does masking the deepest layer affect those on top?


Solution

  • Think of layers as sheets of paper. Think of the view's layer as a big sheet of white paper. As you figured out, the labels' layers are children of the view's layers. To relate, think of the labels' layers being strips of paper glued onto the big view's layer-sheet.

    Let's say you wish to mask the layer with a circle. To translate that into our little analogy, you wish to cover the big view's layer-sheet with Harry Potter's invisibility cloak, with a circle shaped hole in it.

    To do that, you'd cut the invisibility cloak to the same size as that of your view's layer-sheet.

    cloakLayer.frame = bigViewLayer.frame;
    

    Then, you'd carefully cut out a circle from it.

    cloakLayer.path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(0, 0) radius:15.0 startAngle:0.0 endAngle:2 * M_PI clockwise:YES];
    cloakLayer.fillColor = [UIColor blackColor].CGColor; // the hole
    

    Then, you'd paste this cloak-with-a-hole onto your big view's layer-sheet, carefully aligning the edges.

    bigViewLayer.mask = cloakLayer;
    

    What's gonna go invisible? Anything on the sheet (because the cloak was cut to the sheet's dimensions) that doesn't fall into the circle you removed from the cloak. That's the mask property.

    Let's talk about the masksToBounds property.

    Let's say while pasting the strips of label layer-sheets onto the big view's layer-sheet, you decided to place only half of the strip on the sheet, and made the rest hang off the edge(s).

    Let's say you set masksToBounds to YES. What the gods of decoupage would do now is neatly cut off the parts of your labels' strips that are not within the edges of the big view's layer-sheet. That's the masksToBounds property.

    Let's talk about borders. This is simple. Just pick a sharpie of borderColor whose nib is borderWidth points wide, and carefully draw on the edges of the view's layer-sheet. That's it.

    I hope you get things now and can make your own analogies for other properties of the wonderful CALayer.