簡體   English   中英

如何使超級視圖的選定區域透明

[英]How to make selected area of a superview transparent

有什么辦法可以使僅選定的視圖透明區域透明? 我有一個具有黑色(alpha 0.5)背景色的UIView。 我在UIView上放置了一些空心的圓,並希望UIView的下面是透明的,以便可以看穿它。 任何想法

- (id)initWithFrame:(CGRect)iFrame andHollowFrames:(NSArray *)iHollowFrames withRadius:(NSNumber *)iRadius {
    if ((self = [super initWithFrame:iFrame]) != nil) {
        self.hollowFrames =  [[NSSet setWithArray:iHollowFrames] allObjects];
        self.hollowCircleRadius = iRadius;
        [self addShadowView];
    }

    return self;
}


- (void)addShadowView {
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height) cornerRadius:0];

    for (NSValue *point in self.hollowFrames) {
        UIBezierPath *circlePath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(point.CGPointValue.x - self.hollowCircleRadius.floatValue, point.CGPointValue.y - self.hollowCircleRadius.floatValue, 2.0 * self.hollowCircleRadius.floatValue, 2.0 * self.hollowCircleRadius.floatValue) cornerRadius:self.hollowCircleRadius.floatValue];

        [path appendPath:circlePath];
    }

    [path setUsesEvenOddFillRule:YES];

    CAShapeLayer *fillLayer = [CAShapeLayer layer];
    fillLayer.path = path.CGPath;
    fillLayer.fillRule = kCAFillRuleEvenOdd;
    fillLayer.fillColor = [UIColor blackColor].CGColor;
    fillLayer.opacity = 0.5;
    [self.layer addSublayer:fillLayer];
}

這是一個UIView子類解決方案。 為了使它起作用,您必須保留superviews backgroundColor屬性,因為nil witch是默認值。 如果此UIView子類在情節提要中,請確保在屬性檢查器中將背景色設置為“透明色”。

- (void)drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    UIColor *blackBackgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    CGContextSetFillColorWithColor(ctx, blackBackgroundColor.CGColor);
    CGContextFillRect(ctx, rect);
    CGRect transparentPart = CGRectMake(10, 10, 120, 80);
    CGContextClearRect(ctx, transparentPart);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM