UIView鏤空

kim_jin發表於2017-12-13

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

複製程式碼

相關文章