CAGradientLayer涵盖了drawRect中绘制的所有内容

时间:2012-06-13 03:37:32

标签: ios core-graphics calayer

我有以下代码:

-(void)drawRect:(CGRect)rect
{

    // gradient background
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = rect;
    gradient.colors = [NSArray arrayWithObjects:(id) backgroundGradientTop.CGColor, (id) backgroundGradientBottom.CGColor, nil];
    gradient.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0f], [NSNumber numberWithFloat:0.7], nil];

    [self.layer insertSublayer:gradient atIndex:0];



    // line on top
    [[UIColor redColor] set];

    CGContextRef currentContext = UIGraphicsGetCurrentContext();

    CGContextSetLineWidth(currentContext, 5.0f);

    CGContextMoveToPoint(currentContext, 0, 10.0f);

    CGContextAddLineToPoint(currentContext, rect.size.width, 10.0f);

    CGContextStrokePath(currentContext);


}

我试图在渐变顶部绘制的线从未显示过。如果我注释掉渐变层它就在那里。有什么方法可以在顶部绘制渐变背景和线条(或几条线)吗?也许我不应该混合calayer和CG?

1 个答案:

答案 0 :(得分:0)

  

我试图在渐变顶部绘制的线从未显示过。如果我注释掉渐变层,它就在那里。

这是因为子图层出现在其父图层的顶部。您的渐变显然是不透明的,并且与视图大小相同,因此它会覆盖视图。

您不能以这种方式混合CA和CG绘图。如果使用CGContextDrawLinearGradient绘制渐变效果会更好。

相关问题