2010-09-04 91 views
0

下面是我的代码,但它崩溃了...有什么想法?如何放大和裁剪UIImage?

UIImage *tempImage = [[UIImage alloc] initWithData:imageData]; 
CGImageRef imgRef = [tempImage CGImage]; 
[tempImage release]; 

CGFloat width = CGImageGetWidth(imgRef); 
CGFloat height = CGImageGetHeight(imgRef); 
CGRect bounds = CGRectMake(0, 0, width, height); 
CGSize size = bounds.size; 

CGAffineTransform transform = CGAffineTransformMakeScale(4.0, 4.0); 

UIGraphicsBeginImageContext(size); 
CGContextRef context = UIGraphicsGetCurrentContext(); 
CGContextConcatCTM(context, transform); 
CGContextDrawImage(context, bounds, imgRef); 
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

我在这里错过了什么?基本上只是试图缩放图像,并将其裁剪成与原始大小相同。

感谢

+0

哪一种崩溃的?什么是错误信息?什么线路导致崩溃? – vodkhang 2010-09-04 05:13:16

回答

1

的问题是这一行:

CGImageRef imgRef = [tempImage CGImage]; 

或者更准确地说,这条线的直接后续:

[tempImage release]; 

您在这里得到一个CF对象, CGImageRef。核心基础对象只有保留/释放内存管理,但没有自动释放对象。因此,当您在第二行中释放UIImage时,CGImageRef也将被删除。而这又意味着当你试图在那里绘制它时,它是不确定的。

我能想到的三个修正:

  • 使用自动释放延迟图像发布:[tempImage autorelease];
  • 移动释放到你的方法的最底部
  • 保留和使用释放图像CFRetainCFRelease
0

试试这个:

-(CGImageRef)imageCapture 
{ 
    UIGraphicsBeginImageContext(self.view.bounds.size); 
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; 
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    CGRect rect= CGRectMake(0,0 ,320, 480); 

    CGImageRef imageRef = CGImageCreateWithImageInRect([viewImage CGImage], rect); 
    return imageRef; 
} 

使用下面的线,每当你想捕捉的屏幕

UIImage *captureImg=[[UIImage alloc] initWithCGImage:[self imageCapture]];