Search code examples
xcodeuiscrollviewcalayermask

How to mask a UIScrollView?


I currently have an image mask I want to use to mask a UIScrollView. The scrollview holds 1 UIImageView.

Here is what I do at the moment in viewdidload:

CALayer *mask = [CALayer layer];
mask.contents = (id)[UIImage imageNamed:@"ScrollMask.png"].CGImage;
mask.frame = CGRectMake(0, 0, 512, 384);
[Scroll1.layer setMask:mask]; 

This works to some degree. It masks the ImageView inside the scrollview but not the scrollview itself.

Is there a way to mask the scrollview's CALayer and not imageview's layer?


Solution

  • You should put the UIScrollView into a UIView, and then apply the mask to the UIView instead of the UIScrollView.

    CALayer *mask = [CALayer layer];
    mask.contents = (id)[UIImage imageNamed:@"ScrollMask.png"].CGImage;
    mask.frame = CGRectMake(0, 0, 512, 384);
    
    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 512, 384)];
    [containerView.layer setMask:mask];
    
    [containerView addSubview:Scroll1];
    [self.view addSubview:containerView];