1

我正在UIImage向/从网格绘制 s。我目前只绘制更改......并且只有更改......但是旧图像应该留在原地......但是现在它们在下一次调用后消失了drawRect:(CGRect)rect:

- (void)drawRect:(CGRect)rect
{
    int cellSize = self.bounds.size.width / WIDTH;
    double xOffset = 0;

    CGRect cellFrame = CGRectMake(0, 0, cellSize, cellSize);
    NSUInteger cellIndex = 0;
    cellFrame.origin.x = xOffset;
    for (int i = 0; i < WIDTH; i++)
    {        
        cellFrame.origin.y = 0;
        for (int j = 0; j < HEIGHT; j++, cellIndex++)
        {
            if([[self.state.boardChanges objectAtIndex:(i*HEIGHT)+j] intValue]==1){
                if (CGRectIntersectsRect(rect, cellFrame))                {
                    NSNumber *currentCell = [self.state.board objectAtIndex:cellIndex];

                    if (currentCell.intValue == 1)
                    {
                        [image1 drawInRect:cellFrame];
                    }
                    else if (currentCell.intValue == 0)
                    {
                        [image2 drawInRect:cellFrame];
                    }
                }
            }
            cellFrame.origin.y += cellSize;
        }
        cellFrame.origin.x += cellSize;
    }   
}

我尝试了以下混合,但没有任何结果:

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    //CGContextAddRect(context, originalRect);
    CGContextClip(context);    
    [image drawInRect:rect];
    CGContextRestoreGState(context);
4

2 回答 2

0

Cocoa/UIKit 可以随时丢弃之前绘制的视图内容。当您的视图被要求绘制时,它必须在提供的rect. 你不能只是决定不画一些东西。(好吧,你可以做任何你喜欢的事情,但你会得到你所看到的结果。)

于 2013-03-10T03:19:29.680 回答
0

找到另一个解决方案->只需截屏并以drawRect为背景进行绘制。

-(void)createContent{
    CGRect rect = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
    UIGraphicsBeginImageContext(rect.size);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    CGImageRef screenshotRef = CGBitmapContextCreateImage(UIGraphicsGetCurrentContext());
    _backgroundImage = [[UIImage alloc] initWithCGImage:screenshotRef];
    CGImageRelease(screenshotRef);
    UIGraphicsEndImageContext();
}

- (void)drawRect:(CGRect)rect 
{   
    [_backgroundImage drawInRect:CGRectMake(0.0f, 0.0f, self.bounds.size.width, self.bounds.size.height)];
    ....
    ....
    ....
}
######编辑

找到了一种更复杂的方法来完成上述操作: http ://www.cimgf.com/2009/02/03/record-your-core-animation-animation/

#### 编辑

另一种解决方案是使用 CALayers 并且只更新那些改变的部分......

####编辑

或者:

self.layer.contents = (id) [_previousContent CGImage];

于 2013-03-10T13:15:48.890 回答