UIView镂空

811 阅读1分钟

在UIView中镂空其中一块的方法有两种:

- (instancetype)initWithFrame:(CGRect)frame  {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.opaque = NO;
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
   CGRect clearRect = CGRectMake(100, 100, 100, 100);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [[UIColor colorWithRed:0 green:0 blue:0 alpha:0.8] set];
    CGContextAddRect(ctx, self.frame);
    CGContextFillPath(ctx);
// 将混合模式选择为清除
    CGContextSetBlendMode(ctx, kCGBlendModeClear);
    CGContextAddRect(ctx, clearRect);
    CGContextFillPath(ctx);

// 也可直接清除,因为将混合模式设置为清除的话,整个clearRect就会被清除,想要添加边界做成微信扫描的效果比较困难。
// CGClearRect(ctx, clearRect);
}
- (instancetype)initWithFrame:(CGRect)frame  {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.opaque = NO;
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    CGRect clearRect = CGRectMake(100, 100, 100, 100);
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:rect];
    UIBezierPath *rectPath = [UIBezierPath bezierPathWithRect:clearRect];
    [path appendPath:rectPath];
// 设置填充规则
    [path setUsesEvenOddFillRule:YES];

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.fillColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1].CGColor;
    shapeLayer.path = path.CGPath;
    shapeLayer.fillRule = kCAFillRuleEvenOdd;
    shapeLayer.opacity = 0.5;
    [self.layer addSublayer:shapeLayer];
}