CALayer mask does not work properly

I am trying to mask a UIView for an image using its layer mask property. I have seen countless examples that say, "It's just that simple." However, after quite fine tuning, I can not reproduce the described results. Setting a layer mask only reduces the view. Here is the code I'm using:

- (void)setMaskImage:(UIImage *)maskImage { _maskImage = maskImage; self.layer.mask.contents = (__bridge id)(_maskImage.CGImage); } - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self != nil) { self.layer.mask = [CALayer layer]; } return self; } - (void)setFrame:(CGRect)frame { [super setFrame:frame]; self.layer.mask.frame = self.layer.bounds; } 

And here is the image I'm trying to use to mask the view: http://cl.ly/0a300G2r133V

+4
source share
3 answers

The following works as expected:

 - (void)setMaskImage:(UIImage *)maskImage { if (_maskView == nil) { _maskView = [[UIImageView alloc] initWithImage:maskImage]; _maskView.frame = self.bounds; self.layer.mask = _maskView.layer; } else { _maskView.image = maskImage; } } - (UIImage *)maskImage { return _maskView.image; } - (void)setBounds:(CGRect)bounds { [super setBounds:bounds]; _maskView.frame = self.bounds; } 

I'm not sure why just using simple CALayer didn't work, but that adds a bonus to working with stretch images.

+1
source

One possibility is that the system does not use setFrame: to adjust the geometry of your view. It can use setCenter: and setBounds: Another possibility is that the system does not set the geometry of your view at all, and it is set only once in the [super initWithFrame:frame] call before adding a mask layer.

In any case, instead of overriding setFrame: you should override layoutSubviews :

 - (void)layoutSubviews { [super layoutSubviews]; self.layer.mask.frame = self.bounds; } 
+6
source

You can override the UIView drawRect () method for your custom screen appearance. Try the following approach.

 //code for drawRect() CGContextRef context = UIGraphicsGetCurrentContext(); CGContextAddRect(context,ImageFrame); CGContextClip(context); CGContextClearRect(context,ImageFrame); [super drawRect:rect]; 

This will make your image transparent in your imageFrame area.

0
source

Source: https://habr.com/ru/post/1441439/


All Articles