tre*_*nik 3 iphone cocoa-touch memory-management objective-c
我是iPhone应用程序开发的新手,所以我可能做错了.
基本上,我正在从互联网上加载一堆图像,然后裁剪它们.我设法找到了异步加载图像并将它们添加到视图中的示例.我已经设法通过添加一个图像NSData,通过a NSOperation,添加到一个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();
Run Code Online (Sandbox Code Playgroud)
谢谢!
缩放图像的代码看起来太简单了.这是我正在使用的那个.如您所见,没有泄漏,不再需要时释放对象.希望这可以帮助.
// 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2215 次 |
| 最近记录: |