0

我想使用drawLayer:InContext:在 UIView 的 drawRect 方法中循环创建的多个 CALayer 上进行绘制。但drawLayer:InContext:只得到我画的第一层。如何使用此方法在我创建的不同图层上绘图?

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
    CGFloat startingX = [[layer valueForKey:@"StartX"] floatValue];
    NSNumber *heightOfLayer = (NSNumber *)[layer valueForKey:@"Height"];
    CGFloat height = [heightOfLayer floatValue];

    CGContextSetLineWidth(ctx, 3.0);
    CGContextSetStrokeColorWithColor(ctx, [UIColor blueColor].CGColor);
    CGContextBeginPath(ctx);
    CGContextMoveToPoint(ctx, startingX, bottomY);
    CGContextAddLineToPoint(ctx, startingX, bottomY - height);
    CGContextStrokePath(ctx);
}

- (void)drawRect:(CGRect)rect
{
    for (int i = 0; i < valueArray.count; i++) {
        CALayer *subLayer = [CALayer layer];
        subLayer.opaque = YES;
        subLayer.delegate = self;
        subLayer.backgroundColor = [UIColor clearColor].CGColor;

        CGFloat startingX = (20 + 5 * (i + 1));
        subLayer.frame = CGRectMake(startingX, bottomY - [valueArray[i] floatValue], 3.0, [valueArray[i] floatValue]);
        [subLayer setValue:[NSNumber numberWithInt:i] forKey:@"name"];
        [subLayer setValue:[NSNumber numberWithFloat:startingX] forKey:@"StartX"];
        [subLayer setValue:valueArray[i] forKey:@"Height"];
        [self.layer addSublayer:subLayer];
        [subLayer setNeedsDisplay];
    }
}
4

0 回答 0