2 yue1liang1chuan yue1liang1chuan 于 2013.03.14 10:18 提问

绘制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);

1个回答

Kill_it
Kill_it   2013.03.14 16:12

有一个解决方法,做一个屏幕截图,然后用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)];
    ....
    ....
    ....
}
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!