我的代码上有一个非常奇怪的行为。我想在UIGraphicsImageContext中编辑一些图形内容。有时候它有效,有时则不然。我将图像处理功能分离到一个新的线程,如下所示:
-(void)process:(SEL)function withObject:(id)sender {
UIActivityIndicatorView *av = [[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
av.frame = CGRectMake(round((self.view.frame.size.width - 50) / 2),
round((self.view.frame.size.height - 50) / 2), 50, 50);
av.tag = kActivityTag;
[self.view addSubview:av];
[av startAnimating];
[self enableControls:NO];
[NSThread detachNewThreadSelector:function toTarget:self withObject:sender];
在通过以下函数之一调用process函数之前:
-(void)imageColorTintChanged:(id)sender {
[self process:@selector(tint:) withObject:sender];}
-(void)tint:(id)sender {
@synchronized(image) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
float f = ((UISlider *)sender).value;
NSInteger tag = ((UISlider *)sender).tag;
if (tag == 0) {
redTint = f;
} else if (tag == 1) {
greenTint = f;
} else if (tag == 2) {
blueTint = f;
}
previewImage = [ImageUtil colorizeImage:image color:[UIColor colorWithRed:redTint green:greenTint blue:blueTint alpha:1.0]];
[imageView setImage:previewImage];
[self processDidFinish];
[pool release];
}}
最后,我的图形编辑从新线程开始:
+ (UIImage *)colorizeImage:(UIImage *)baseImage color:(UIColor *)theColor {
if (baseImage) {
@synchronized (baseImage) {
UIGraphicsBeginImageContext(baseImage.size); // CRASH!!
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect area = CGRectMake(0.0f, 0.0f, baseImage.size.width, baseImage.size.height);
CGContextTranslateCTM(ctx, 0.0, baseImage.size.height);
CGContextScaleCTM(ctx, 1.0, -1.0);
[theColor set];
CGContextFillRect(ctx, area);
CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
CGContextDrawImage(ctx, area, baseImage.CGImage);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
}
return baseImage;
大部分时间它在这一行崩溃:
UIGraphicsBeginImageContext(baseImage.size);
它可能是什么?一个穿线的东西? 提前谢谢。
编辑:
好吧,我在Instruments上做了一个活动监视器测试,由于某种原因它没有内存泄漏,但实际的内存使用量在一些图像处理之后上升到53 MB然后崩溃了。是否有可能只是“我使用太多内存”错误?
答案 0 :(得分:1)
来自UIKit Function Reference,关于UIGraphicsBeginImageContext()
:
您应该只从应用程序的主线程调用此函数。
您需要在此处创建CGBitmapContext
。