Search code examples
iosobjective-ccore-graphicscalayer

Move a CALayer frame but not the clip mask


I would like the move a layer by setting its frame, but without the layer clip being moved as well.

I have created a layer which is created as follows:

layer = [CustomLayer layer];
layer.frame = CGRectMake(50, 50, 100, 30);
[layer setNeedsDisplay];
[self.view.layer addSublayer:layer];

And a clip layer like so:

clipLayer = [CAShapeLayer layer];
UIBezierPath *clipPath = [UIBezierPath bezierPathWithRoundedRect:layer.bounds
                                                    cornerRadius:10.0f];
clipLayer.path = clipPath.CGPath;
layer.mask = clipLayer;

However, at some later point in my code, if I set the layer frame:

layer.frame = CGRectOffset(layer.frame, -20.0, 0.0);

Both the layer and its clip mask are offset. The effect I am trying to achieve is to 'scroll' a layer beneath a rounded rectangular clipping area. Any ideas?


Solution

  • I would clip the clip layer to a third layer.This third layer needs to:

    • be of the same size of the layer you want to mask
    • be at the same position of the layer you want to mask
    • have clearColor background color

    then just move the underlying layer and third layer with its clipped layer will stay put.

    NOTE: This worked for me - although, you also have to ensure that the layer being moved is a subview of the clipping layer.