绘制context不影响以前的

正在从grid绘制UIImage,目前在绘制修改。原来的图片应该不会受影响,但是现在调用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);

有一个解决方法,做一个屏幕截图,然后用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)];
    ....
    ....
    ....
}