【问题标题】:How to create a oval clear color view inside a UIView? [closed]如何在 UIView 中创建椭圆形清晰的颜色视图? [关闭]
【发布时间】:2020-11-05 15:50:50
【问题描述】:

我想在当前视图控制器之上创建 UIView 以显示为一个小弹出窗口。但是这个视图有一个椭圆形的透明颜色背景视图,可以通过特定的按钮显示。图像如下所示。整个视图是一个灰色透明视图,下面有一个清晰的彩色视图在里面。如何创建这样的东西?

【问题讨论】:

    标签: ios objective-c swift uiview


    【解决方案1】:

    您可以添加带有遮罩的附加层, 将形成“透明”区域。这里是实现这个效果的程序代码。

        - (void) createOverlay
    {
        UIView *overlayView = [[UIView alloc] initWithFrame:self.view.frame];
        overlayView.alpha = 0.75;
        overlayView.backgroundColor = [UIColor darkGrayColor];
        [self.view addSubview:overlayView];
        
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        CGMutablePathRef path = CGPathCreateMutable();
        
        CGFloat offsetX = self.view.frame.size.width / 6.0;
        CGFloat offsetY = self.view.frame.size.height / 8.0;
        CGFloat ovalWidth = self.view.frame.size.width - offsetX * 2.0;
        CGFloat ovalHeight = self.view.frame.size.height - offsetY * 3.0;
        CGRect ovalRect = CGRectMake(offsetX, offsetY, ovalWidth, ovalHeight);
    
        
        CGPathAddEllipseInRect(path, nil, ovalRect);
        CGPathAddRect(path, nil, CGRectMake(0, 0, overlayView.frame.size.width, overlayView.frame.size.height));
        
        maskLayer.backgroundColor = [UIColor darkGrayColor].CGColor;
        
        maskLayer.path = path;
        maskLayer.fillRule = kCAFillRuleEvenOdd;
        
        // Release the path since it's not covered by ARC.
        overlayView.layer.mask = maskLayer;
        overlayView.clipsToBounds = YES;
        
        UIBezierPath *ovalPath = [UIBezierPath bezierPathWithOvalInRect:ovalRect];
        CAShapeLayer *lineLayer = [[CAShapeLayer alloc] init];
        lineLayer.path = ovalPath.CGPath;
        lineLayer.fillColor = [UIColor clearColor].CGColor;
        lineLayer.strokeColor = [UIColor grayColor].CGColor;
        lineLayer.lineWidth = 1;
        lineLayer.fillRule = kCAFillRuleEvenOdd;
        
        [self.view.layer addSublayer:lineLayer];
    
        [self.view bringSubviewToFront:self.buttonView];
        [self.view bringSubviewToFront:self.switchView];
        [self.view bringSubviewToFront:self.timeLabel];
        
        self.timeLabel.text = @"";
    }
    

    【讨论】:

    • 很好 - 我真的很喜欢这个解决方案。我什至喜欢(舞台外)飞机和汽车!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    • 2017-12-22
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多