在重写 UIView drawRect 时,我使用 CGContextDrawImage 绘制主图像。在它上面我需要绘制另一个图像(使用多重混合模式),所以我实际上需要在它上面绘制。
第二个图像需要准备,因为它是动态生成的(它必须被屏蔽,可能大小不同等等),所以最后我需要生成它。如何获得第二个上下文,在将第二个图像应用到主图像上之前,我可以在其中绘制并 mask 第二个图像?如果我在当前上下文上进行绘制,那么在我可以屏蔽它之前,它会直接绘制到主上下文中。
- (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现在包含正确的图像,但由于我已经使用主上下文准备了它,所以它并不完全困惑。谢谢
谢谢
最佳答案
您可以使用 UIGraphicsBeginImageContextWithOptions
创建位图上下文或CGBitmapContextCreate
。在位图上下文中完成绘制后,您可以使用 UIGraphicsGetImageFromCurrentImageContext
或 CGBitmapContextCreateImage
(根据需要)获取图像,然后使用 UIGraphicsEndImageContext 释放上下文
或 CGContextRelease
。
关于iphone - drawRect 中的多个 CGContextRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13579149/