2011-02-28 110 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];