【发布时间】:2020-11-05 15:50:50
【问题描述】:
我想在当前视图控制器之上创建 UIView 以显示为一个小弹出窗口。但是这个视图有一个椭圆形的透明颜色背景视图,可以通过特定的按钮显示。图像如下所示。整个视图是一个灰色透明视图,下面有一个清晰的彩色视图在里面。如何创建这样的东西?
【问题讨论】:
标签: ios objective-c swift uiview
我想在当前视图控制器之上创建 UIView 以显示为一个小弹出窗口。但是这个视图有一个椭圆形的透明颜色背景视图,可以通过特定的按钮显示。图像如下所示。整个视图是一个灰色透明视图,下面有一个清晰的彩色视图在里面。如何创建这样的东西?
【问题讨论】:
标签: ios objective-c swift uiview
您可以添加带有遮罩的附加层, 将形成“透明”区域。这里是实现这个效果的程序代码。
- (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 = @"";
}
【讨论】: