【问题标题】:Making UIView transparent使 UIView 透明
【发布时间】:2013-03-15 05:07:58
【问题描述】:

我想向我的 UIViewController 添加一个 UIView,但我希望它是透明的,直到我决定在 UIView 中创建一个椭圆形。

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

这是一堆椭圆的样子

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

【问题讨论】:

    标签: ios uiview screen transparent


    【解决方案1】:

    请尝试使用这个

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

    【讨论】:

    • 透明:view.isOpaque = false
    • 使用UIColor.clear 将是对所有地方的代码进行标准化的更好选择。
    【解决方案2】:
    - (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];
    }
    

    【讨论】:

      【解决方案3】:

      在你的 ViewController 中,你可以说 opaque 是 NO。假设您的视图名为 myCustomView。

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

      或者你可以直接去情节提要并取消选中不透明的复选框,例如 -

      【讨论】:

        【解决方案4】:

        在 Swift 3.x 中:(其中 layerview

        layer.backgroundColor = UIColor.clear.cgColor
        layer.isOpaque = false
        

        【讨论】:

        • 我得到一个异常“在隐式展开可选值时意外发现 nil”
        • Swift 是一种不断发展的语言,您使用的是哪个版本?
        【解决方案5】:

        我为我的 UIViewController 做了半透明背景,就像这里推荐的那样,但是直到我将 modalPresentationStyle 设置为 .custom

        后它才起作用

        我的 Swift 4 代码:

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

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

        【讨论】:

        • 感谢您的提示。在看到您的答案之前,我一直在为此挠头。我将modalPresentationStyle 更改为.custom,它也对我有用!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-21
        • 2014-12-09
        • 2014-08-03
        • 1970-01-01
        相关资源
        最近更新 更多