使UIView透明化

21

我想将一个UIView添加到我的UIViewController中,但在我决定在UIView内创建椭圆之前,我希望它是透明的。

在我创建椭圆之前,我可以将视图的alpha设置为0,但当我想添加椭圆时,背景色仍然是黑色。

这是一堆椭圆的样子:

image

在我的UIView中:

- (void)drawRect:(CGRect)rect
{
    [self pushContext];
    UIBezierPath *oval = [UIBezierPath bezierPathWithOvalInRect:self.bounds];
    [[UIColor redColor] setFill];
    [oval fill];
    self.opaque = NO;
    [self setBackgroundColor:[UIColor clearColor]];

    [oval addClip];
    [self setBackgroundColor:[UIColor clearColor]];

    [self popContext];
}
5个回答

29

请尝试使用这个

view.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.0];
view.opaque = NO;

使其透明:view.isOpaque = false - spencer.sm
2
使用 UIColor.clear 将是更好的选择,以便在整个代码中进行标准化。 - Cheok Yan Cheng

19
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code

        self.opaque = NO;

    }
    return self;
}



- (void)drawRect:(CGRect)rect
{
    [[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.0] setFill];
    UIRectFill(rect);
    [self pushContext];
    UIBezierPath *oval = [UIBezierPath bezierPathWithOvalInRect:self.bounds];
    [[UIColor redColor] setFill];
    [oval fill];

    [oval addClip];

    [self popContext];
}

5

在您的ViewController中,您可以说不透明是NO。假设,您的视图名为myCustomView。

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myCustomView.opaque = NO;   
}

或者你可以直接进入故事板并取消不透明复选框,像这样- enter image description here


4

我按照这里推荐的方法为我的UIViewController设置了半透明背景,但直到我将modalPresentationStyle设置为.custom后才生效。

我的Swift 4代码:

modalPresentationStyle = .custom
view.isOpaque = false
view.backgroundColor = UIColor.black.withAlphaComponent(0.2)

我使用present(controller, anim, completion)方法从另一个控制器打开我的控制器。


谢谢你的提示。我一直在苦思冥想,直到看到你的答案。我将 modalPresentationStyle 更改为 .custom,这对我也起作用了! - Brian Sachetta

3
在Swift 3.x中:(其中 layer 是 view )
layer.backgroundColor = UIColor.clear.cgColor
layer.isOpaque = false

我得到了一个异常 "在隐式解包可选值时意外地发现了 nil"。 - Pravalika
Swift是一门不断发展的语言,你使用的是哪个版本? - Matt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接