2012-11-27 31 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釋放上下文。