【发布时间】:2011-01-23 19:23:34
【问题描述】:
我从 drawRect 调用下面的代码
- (void) drawPartial:(UIImage *)img colour:(UIColor *)colour {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, self.frame, img.CGImage);
if (colour!=nil) {
CGContextSetBlendMode (context, kCGBlendModeColor );
CGContextClipToMask(context, self.bounds, img.CGImage);
CGContextSetFillColor(context, CGColorGetComponents(colour.CGColor));
CGContextFillRect (context, self.bounds);
}
self.currentImage=UIGraphicsGetImageFromCurrentImageContext();
CGContextRestoreGState(context);
}
事实上,我多次调用它来构建一个动态着色的合成图像。传入的每个 img 实际上是一个透明覆盖层,上面有图像的不同部分。
我可以通过在drawrect中多次调用它来构建我的复合图像。当我想更新图像的一部分时,问题就来了。理想情况下,我可以调用上述函数并只更改一个部分:我尝试过使用 self.clearsContextBeforeDrawing 无济于事。
然后我想我会尝试保留每次绘制的图像副本,作为状态的缓存图像 - 这样我只需要在其上覆盖新部分:两次调用而不是 15 次。
但是 self.currentImage=UIGraphicsGetImageFromCurrentImageContext() 行没有返回当前图像,因此我无法构建缓存副本。
对于这两种方法的任何帮助将不胜感激。 (或者显然指出我应该这样做的方式!)
编辑 我还尝试使用几乎相同的代码分别合成图像,然后绘制它,但我还是没有得到图像......
- (UIImage *) overlayImage:(UIImage *)srcImage withImage:(UIImage *)overlayImage ofColour:(UIColor *)colour {
CGSize size =srcImage.size;
CGRect box = CGRectMake(0, 0, size.width, size.height);
UIGraphicsBeginImageContext(size);
CGContextRef context=UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0.0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, box, srcImage.CGImage);
if (colour!=nil) {
CGContextSetBlendMode (context, kCGBlendModeColor ); //kCGBlendModeMultiply
CGContextClipToMask(context, box, overlayImage.CGImage); // respect alpha mask
CGContextSetFillColor(context, CGColorGetComponents(colour.CGColor));
CGContextFillRect (context, box);
}
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
//UIImage *result = [UIImage imageWithCGImage: CGBitmapContextCreateImage (context)];
UIGraphicsEndImageContext();
return result;
}
【问题讨论】:
-
您无法从默认绘制上下文中获取图像。如果您使用 UIGraphicsBeginImageContext 明确地开始一个单独的(屏幕外)上下文,则只能获得一个。
标签: iphone cocoa-touch uikit core-graphics