[英]Multiple Image Operations Crash iPhone App
我是iPhone App開發的新手,所以可能我做錯了。
基本上,我從互聯網上加載了一堆圖像,然后進行裁剪。 我設法找到了異步加載圖像並將其添加到視圖中的示例。 我設法通過添加到NSOperation
與NSData
添加圖像來做到這NSOperationQueue
。
然后,由於必須制作固定大小的拇指,因此需要一種裁剪圖像的方法,因此我在網上找到了一個腳本,該腳本基本上使用UIGraphicsBeginImageContext()
, UIGraphicsGetImageFromCurrentImageContext()
和UIGraphicsEndImageContext()
繪制裁剪后的圖像,不重要的尺寸計算。
事實是,該方法有效,但是由於它生成了20張這樣的圖像,因此在生成了其中一些圖像后,或者有時在我關閉並重新打開該應用程序一兩次后,它隨機崩潰。
在這種情況下我該怎么辦? 我也嘗試使用NSOperations
和NSOperationQueue
使此方法以某種方式異步運行,但是沒有運氣。
如果作物代碼比我想像的更相關,則為:
UIGraphicsBeginImageContext(CGSizeMake(50, 50));
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = CGPointMake(0.0,0.0); //this is actually generated
// based on the sourceImage size
thumbnailRect.size.width = 50;
thumbnailRect.size.height = 50;
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
謝謝!
縮放圖像的代碼看起來太簡單了。 這是我正在使用的那個。 如您所見,沒有泄漏,不再需要時釋放對象。 希望這可以幫助。
// Draw the image into a pixelsWide x pixelsHigh bitmap and use that bitmap to
// create a new UIImage
- (UIImage *) createImage: (CGImageRef) image width: (int) pixelWidth height: (int) pixelHeight
{
// Set the size of the output image
CGRect aRect = CGRectMake(0.0f, 0.0f, pixelWidth, pixelHeight);
// Create a bitmap context to store the new thumbnail
CGContextRef context = MyCreateBitmapContext(pixelWidth, pixelHeight);
// Clear the context and draw the image into the rectangle
CGContextClearRect(context, aRect);
CGContextDrawImage(context, aRect, image);
// Return a UIImage populated with the new resized image
CGImageRef myRef = CGBitmapContextCreateImage (context);
UIImage *img = [UIImage imageWithCGImage:myRef];
free(CGBitmapContextGetData(context));
CGContextRelease(context);
CGImageRelease(myRef);
return img;
}
// MyCreateBitmapContext: Source based on Apple Sample Code
CGContextRef MyCreateBitmapContext (int pixelsWide,
int pixelsHigh)
{
CGContextRef context = NULL;
CGColorSpaceRef colorSpace;
void * bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;
bitmapBytesPerRow = (pixelsWide * 4);
bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);
colorSpace = CGColorSpaceCreateDeviceRGB();
bitmapData = malloc( bitmapByteCount );
if (bitmapData == NULL)
{
fprintf (stderr, "Memory not allocated!");
CGColorSpaceRelease( colorSpace );
return NULL;
}
context = CGBitmapContextCreate (bitmapData,
pixelsWide,
pixelsHigh,
8,
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast);
if (context== NULL)
{
free (bitmapData);
CGColorSpaceRelease( colorSpace );
fprintf (stderr, "Context not created!");
return NULL;
}
CGColorSpaceRelease( colorSpace );
return context;
}
您的應用程序崩潰是因為您正在使用的調用(例如,UIGraphicsBeginImageContext)操縱了UIKit的上下文堆棧,您只能從主線程安全地執行此操作。
unforgiven的解決方案在線程中使用時不會崩潰,因為它不會操縱上下文堆棧。
聽起來確實像是內存不足崩潰。 啟動泄漏工具,查看整體內存趨勢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.