2

在我的 iPad 绘图应用程序中,我有一个 768 x 1024 的缓冲区上下文,我创建并使用它来加速我的绘图。

这是调用 drawRect 时我当前正在执行的代码,它只是将我已经存在的绘图复制到屏幕上:

CGContextRef context = UIGraphicsGetCurrentContext();

CGImageRef image = CGBitmapContextCreateImage([DrawingState sharedState].context);
CGContextDrawImage(context, CGRectMake(0, 0, 768, 1024), image);
CGImageRelease(image);

此代码按预期工作:它从我的背景上下文中收集图像并将其绘制到我当前的上下文中,然后释放图像。有用!

但是,我正在做一些性能调整以加快绘图速度,我正在尝试使用此代码,其中“rect”是 drawRect 传入的矩形

CGContextRef context = UIGraphicsGetCurrentContext();

CGImageRef image = CGBitmapContextCreateImage([DrawingState sharedState].context);
CGImageRef subImage = CGImageCreateWithImageInRect(image, rect);
CGContextDrawImage(context, rect, subImage);
CGImageRelease(subImage);
CGImageRelease(image);

这不起作用;图像没有出现在正确的位置,甚至可能不是正确的图像(无法判断,因为如果图像出现在错误的位置,图像的一部分甚至不会绘制,因为它会在 drawRect 之外矩形。)知道发生了什么吗?

下面是我如何初始化 [DrawingState sharedState].context。这部分应该没问题,但我想我会把它包括在内以保持完整性。

if(context != NULL)
{
    CGContextRelease(context);
    context = NULL;
}
if(bitmapData != NULL)
{
    free(bitmapData);
    bitmapData = NULL;
}
if(colorSpace != NULL)
{
    CGColorSpaceRelease(colorSpace);
    colorSpace = NULL;
}

CGSize canvasSize = CGSizeMake(screenWidth, screenHeight);

int bitmapByteCount;
int bitmapBytesPerRow;

bitmapBytesPerRow   = (canvasSize.width * 4);
bitmapByteCount     = (bitmapBytesPerRow * canvasSize.height);

colorSpace = CGColorSpaceCreateDeviceRGB();

bitmapData = malloc( bitmapByteCount );

if( bitmapData == NULL ){
    NSLog(@"Buffer could not be alloc'd");
}

//Create the context
context = CGBitmapContextCreate(bitmapData, canvasSize.width, canvasSize.height, 8, bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedFirst);

根据要求,我尝试执行的实际优化如下。我正在将缓冲区图像(在进行其他绘制之前)绘制到我的缓冲区上下文中,然后将我的缓冲区上下文复制到当前上下文中。

原始代码:

CGContextClearRect([DrawingState sharedState].context, CGRectMake(0, 0, 768, 1024));
if(bufferImage != NULL)
{
    CGContextDrawImage([DrawingState sharedState].context, CGRectMake(0, 0, 768, 1024), bufferImage);
}

优化代码:

CGContextClearRect([DrawingState sharedState].context, rect);
if(bufferImage != NULL)
{
    CGImageRef subImage = CGImageCreateWithImageInRect(bufferImage, rect);
    CGContextDrawImage([DrawingState sharedState].context, rect, bufferImage);
    CGImageRelease(subImage);
}
4

2 回答 2

0

这个问题的简短答案是我想使用 CGContextClipToRect 而不是尝试获取子图像。CGContextClipToRect(CGContextRef, CGRect) 用于自动将任何绘图剪辑到提供的矩形之外的上下文中。

于 2012-08-29T15:29:02.357 回答
0

我怀疑你想使用相同的rect值来创建子图像和绘图。

如果您阅读文档CGImageCreateWithImageInRect获取图像和 rect 参数的交集,同时CGContextDrawImage将图像绘制成 rect。

我不知道您打算如何将其用作优化,但您的结果听起来像我对您的代码的期望。

于 2012-08-22T15:13:38.040 回答