是否可以在块中绘制 CGContext?

Is it possible draw CGContext in blocks?

在 IOS,我有一个 NSArray 存储 blocks 在 UIView 上绘制一些东西,例如:

^(CGContextRef ctx) {
    // drawing rectangle
    CGRect rect = CGRectMake(0, 0, 300, 300);
    CGContextSetRGBFillColor(ctx, 1, 0, 0, 1);
    CGContextFillRect(ctx, rect);
    CGContextStrokeRect(ctx, rect);
};

数组中会存储几个块,我希望这些块在 drawRect 被调用时依次执行,这是我的 drawRect

- (void)drawRect:(CGRect)rect {
    // execute blocks 
    for(NSDictionary * task in drawTaskQueue)
    {
        DrawTaskBlock block = [task objectForKey:@"block"];
        block(args, UIGraphicsGetCurrentContext());
    }
}

但是当我 运行 代码时,我确定这些块已正确执行,但没有显示任何内容。我错过了什么吗?

您的代码的问题是您传递的块需要一个 CGContextRef 类型的参数,而调用代码传递两个参数 - argsUIGraphicsGetCurrentContext() .

由于 Objective-C 不检查转换,您的块最终 运行 错误的图形上下文,导致未定义的行为。

要解决此问题,您需要确保方块的 "signature" 与您将其投射到的方块类型的签名相匹配,即 DrawTaskBlock。签名必须包含 args 参数的正确类型,即使 none 块正在使用它。