2010-09-04 92 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]];