2013-03-15 106 views
10

我想添加一個UIView到我的UIViewController,但我希望它是透明的,直到我決定在UIView內創建一個Oval。使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]; 
} 

回答

13
- (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]; 
} 
+0

哦有趣的解決方案!非常感謝 – peter1234 2013-03-15 06:15:23

22

請儘量使用這一個

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

在你的ViewController,你可以說不透明是NO。假設您的視圖名爲myCustomView。

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

或者您也可以去到故事板並取消不透明覆選框喜歡 - enter image description here