CALayer - 清除内部渲染上下文,支持自定义绘图代码

时间:2011-03-25 20:38:16

标签: objective-c cocoa core-graphics calayer quartz-graphics

当继承CALayer并实现drawInContext方法时,我会假设我在那里做的任何绘图都会显示,但是如果我设置(例如)borderWidth / borderColor,那么CALayer将在其上绘制一个边框拥有我自己的自定义绘图代码。

这是一个CALayer子类:

@implementation MyCustomCALayer

- (id)init  
{  
    self = [super init];  

    if(self)  
    {  
        [self setNeedsDisplayOnBoundsChange:YES];  
    }  

    return self;  
}  

- (void)drawInContext:(CGContextRef)context  
{  
    CGRect rect = CGContextGetClipBoundingBox(context);  

    CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);  
    CGContextFillRect(context, rect);  
}  

@end  

- (id)init { self = [super init]; if(self) { [self setNeedsDisplayOnBoundsChange:YES]; } return self; } - (void)drawInContext:(CGContextRef)context { CGRect rect = CGContextGetClipBoundingBox(context); CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor); CGContextFillRect(context, rect); } @end

在UIView中创建如下:

- (void)ensureLayer
{
if(myLayer)
return;

    myLayer = [[[MyCustomCALayer alloc] init] autorelease];  
    myLayer.borderColor = [UIColor greenColor].CGColor;  
    myLayer.borderWidth = 1;  
    myLayer.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);  
}  

- (void)layoutSublayersOfLayer:(CALayer *)layer  
{  
    [super layoutSublayersOfLayer:layer];  
    [self ensureLayer];  

    if(![[layer.sublayers objectAtIndex:0] isEqual:myLayer])  
        [layer insertSublayer:myLayer atIndex:0];  
}  

会发生什么,是MyCustomCALayer用红色填充一个矩形,这是我期望看到的,没有别的,因为我已经实现了drawInContext方法,但我看到一个顶部带有绿色边框的红色矩形,总是排在最前面,我已经尝试了几乎所有我能想到的组合,以摆脱被绘制的绿色边界,无法弄明白。

我的理由是我想使用borderWidth和borderColor以及CALayer的其他属性而不是创建我自己的属性,因为我需要绘制的代码包含边框,填充等...但渲染我需要做的不是一个简单的形状。所以我找到的唯一方法就是将borderWidth设置为0并将我自己的属性添加到我的子类中,就像myBorderWidth一样,这很荒谬。

这是使用最新的iOS SDK完成的,但我认为它与Mac相同。

希望这有意义,有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

你运气不好; CoreAnimation不支持覆盖基本图层属性的渲染实现。请file a bug