How to mask a UIScrollView?

2020-02-29 04:21发布

问题:

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?

回答1:

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];