0

我发现了许多如何将 int 数组 blit 到UIViewin的示例drawRect,但最简单的一个仍然让我感到困惑。这工作正常,但仍然有三个问题:

~ 为什么有两个上下文?

〜为什么push/pop上下文?

~ 可以避免复制吗?苹果文档说 CGBitmapContextCreateImage 复制内存块)

- (void)drawRect:(CGRect)rect {
    CGColorSpaceRef color = CGColorSpaceCreateDeviceRGB();
    int PIX[9] = {  0xff00ffff,0xff0000ff,0xff00ff00,
                        0xff0000ff,0xff00ffff,0xff0000ff,
                        0xff00ff00,0xff0000ff,0xff00ffff};
    CGContextRef context = CGBitmapContextCreate((void*)PIX,3,3,8,4*3,color,kCGImageAlphaPremultipliedLast);
    UIGraphicsPushContext(context);
    CGImageRef image = CGBitmapContextCreateImage(context);
    UIGraphicsPopContext();
    CGContextRelease(context);
    CGColorSpaceRelease(color);
    CGContextRef c=UIGraphicsGetCurrentContext();
    CGContextDrawImage(c, CGRectMake(0, 0, 10, 10), image);
    CGImageRelease(image);
}
4

1 回答 1

0

该方法将数组绘制为 3x3 大小的图像,然后在当前上下文中将该图像绘制为 10x10 大小,在这种情况下将是您UIViewCALayer.

UIGraphicsPushContext让您设置CGContext当前正在绘制的对象。因此,在第一次调用之前,您的当前CGContextUIView,然后您推送新CGContext的,即正在绘制的图像。

UIGraphicsPopContext调用恢复先前的上下文,即UIView,然后您获得对该上下文的引用,并使用以下行将创建的图像绘制到它:

CGContextDrawImage(c, CGRectMake(0, 0, 10, 10), image);

至于避免复制操作,文档说它有时是写入时的副本,但他们没有指定这些条件何时发生:

The CGImage object returned by this function is created by a copy operation. Subsequent changes to the bitmap graphics context do not affect the contents of the returned image. In some cases the copy operation actually follows copy-on-write semantics, so that the actual physical copy of the bits occur only if the underlying data in the bitmap graphics context is modified. As a consequence, you may want to use the resulting image and release it before you perform additional drawing into the bitmap graphics context. In this way, you can avoid the actual physical copy of the data.

于 2013-03-25T04:38:15.430 回答