2012-11-27 35 views
0

在重写UIView drawRect时,我使用CGContextDrawImage绘制主图像。在它上面,我需要绘制另一个图像(使用多种混合模式),所以我实际上需要通过来绘制drawRect中的多CGContextRef

这第二个图像需要准备,因为它是动态生成的(它必须被屏蔽,可能是不同的大小等等),所以最后我需要生成它。我怎么能得到第二个上下文,我可以绘制和掩盖这第二个图像之前应用它在主要的?如果我借鉴当前的情况,在我能够掩盖它之前,它会被直接绘制出来。

- (void) drawRect:(CGRect)rect 
{ 
    CGContextRef ctx = UIGraphicsGetCurrentContext(); 

    CGContextDrawImage(ctx, CGRectMake(0, 0, rect.size.width, rect.size.height), [UIImage imageNamed:@"actionBg.png"].CGImage); 

    // prevent the drawings to be flipped 
    CGContextTranslateCTM(ctx, 0, rect.size.height); 
    CGContextScaleCTM(ctx, 1.0, -1.0); 

    // generate the overlay 
    if ([self isActive] == NO && self.fullDelay != 0) { // TODO: remove fullDelay check! 
     int segmentSize = (ACTION_SIZE/[self fullDelay]); 

     for (int i=0; i<[self fullDelay]; i++) { 
      float alpha = 0.9 - (([self fullDelay] * 0.1) - (i * 0.1)); 
      [[UIColor colorWithRed:120.0/255.0 green:14.0/255.0 blue:14.0/255.0 alpha:alpha] setFill]; 

      if (currentDelay > i) { 
       CGRect r = CGRectMake(0, i * segmentSize, ACTION_SIZE, segmentSize); 
       CGContextFillRect(ctx, r); 
      } 
      [[UIColor colorWithRed:1 green:1 blue:1 alpha:0.3] setFill]; 
      CGRect line = CGRectMake(0, (i * segmentSize) + segmentSize - 1 , ACTION_SIZE, 1); 
      CGContextFillRect(ctx, line); 
     } 

     UIImage *overlay = UIGraphicsGetImageFromCurrentImageContext(); 
     UIImage *overlayMasked = [TDUtilities maskImage:overlay withMask:[UIImage imageNamed:@"actionMask.png"]]; 
    } 
} 

这里overlayMasked现在包含正确的图像,但因为我已经准备使用它的主要方面,它是不是全乱。由于

感谢

回答

1

您可以使用UIGraphicsBeginImageContextWithOptionsCGBitmapContextCreate创建位图上下文。在完成位图上下文绘制后,可以使用UIGraphicsGetImageFromCurrentImageContextCGBitmapContextCreateImage(根据需要)获取图像,然后使用UIGraphicsEndImageContextCGContextRelease释放上下文。