Mask a UIView with a cut-out circle

前端 未结 3 1031
南旧
南旧 2020-12-13 21:09

I’ve created a UIView with a semi-transparent black background to sit across my main app’s view. What I’m aiming for here is to create a cut-out circle shape so

3条回答
  •  鱼传尺愫
    2020-12-13 21:23

    So, here’s what I did. I created a custom UIView subclass called BlackoutView, like so:

    BlackoutView.h

    #import 
    
    @interface BlackoutView : UIView
    
    @property (nonatomic, retain) UIColor *fillColor;
    @property (nonatomic, retain) NSArray *framesToCutOut;
    
    @end
    

    BlackoutView.m

    #import "BlackoutView.h"
    
    @implementation BlackoutView
    
    - (void)drawRect:(CGRect)rect
    {
        [self.fillColor setFill];
        UIRectFill(rect);
    
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetBlendMode(context, kCGBlendModeDestinationOut);
    
        for (NSValue *value in self.framesToCutOut) {
            CGRect pathRect = [value CGRectValue];
            UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:pathRect];
            [path fill];
        }
    
        CGContextSetBlendMode(context, kCGBlendModeNormal);
    }
    
    @end
    

    I then instantiate it as normal, and set the properties to the colour of the mask I want to use, and the frames to be cut out of the mask:

    [blackMask setFillColor:[UIColor colorWithWhite:0.0f alpha:0.8f]];
    [blackMask setFramesToCutOut:@[[NSValue valueWithCGRect:buttonCircleA.frame],
                                   [NSValue valueWithCGRect:buttonCircleB.frame]]];
    

    This could be improved by allowing me to cut out other shapes besides ovals, but it’s fine for my purposes here and would be easily adapted to do so later. Hopefully this helps others!

提交回复
热议问题