2011-02-28 59 views
10

我想在CG中獲得透明背景,但它始終呈現黑色。CoreGraphics中的透明背景

我有以下代碼:

- (id)initWithFrame:(CGRect)frame { 
    if ((self = [super initWithFrame:frame])) { 
     DLog(@">>> Alloc: DrawingCanvas [0x%X]", (unsigned int)self); 
     [self setOpaque:NO]; 
     [self setBackgroundColor:[UIColor clearColor]]; 
    } 
    return self; 
} 

- (void) drawRect:(CGRect)rect 
{ 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGRect frame = rect; 
    int counter = 3; 

    CGContextClearRect(context, frame); 
    CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor); 
    CGContextFillRect(context, frame); 
} 

我如何獲得此代碼顯示一個透明的背景是什麼?

+0

您是否找到解決方案?如果是這樣,請通過回答您自己的問題分享。 – 2011-04-22 18:44:41

回答

4

使用該設置,只要您沒有將clearsContextBeforeDrawing設置爲NO,當您調用drawRect:方法時背景應該已經透明。除去CGContextClearRect和其他繪圖調用。只要您設置不透明的NO和clearColor作爲一切的backgroundColor應罰款

CGContextClearRect(context, frame); 
CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor); 
CGContextFillRect(context, frame); 

+0

我會在另一個地方使用相同的(類似的)代碼,我得到一個上下文並且每次都必須清除它,所以我沒有看到我將能夠移除對'CGContextClearRect'的調用 - 除非我能以不同的方式清除它? – Egil 2011-03-01 04:11:09

3

你可以簡單地刪除這些行。

繪圖時要小心,因爲您的其他繪圖代碼可能會完全填充背景(在非剪裁的上下文中處理[path fill]事情)。

1

我有這個相同的問題,解決的辦法是設置我從父視圖的類中繪製的UIView的backgroundColor屬性。我不需要任何代碼來清除繪圖發生的UIView類中的背景。

myDrawingView.backgroundColor = [UIColor clearColor];