我正在使用以下代码在我的iOS应用程序上触摸的图形屏幕截图:
:dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
if(_pagessavedbg.count > selectedIndex)
self.topimage = [_pagessavedbg objectAtIndex:selectedIndex];
else
self.topimage = [UIImage imageNamed:@"BlankImage.png"];
UIImage *bottomimage = [notification.userInfo objectForKey:@"Image"];
CGSize size = activeView.frame.size;
NSUInteger width = size.width * 2;
NSUInteger height = size.height * 2;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
memset(rawData,0,height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGRect bounds;
bounds.origin = CGPointMake(0,0);
bounds.size = size;
CGContextScaleCTM(context, 2.0, 2.0);
CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), [self.topimage CGImage]);
CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), [bottomimage CGImage]);
CGImageRef imageRef2 = CGBitmapContextCreateImage(context);
UIImage *latest2 = [UIImage imageWithCGImage:imageRef2 scale:0.0 orientation:UIImageOrientationDownMirrored];
activeView.layer.contentsScale = 2.0;
[activeView.layer renderInContext:context];
CGImageRef imageRef = CGBitmapContextCreateImage(context);
UIImage *latest = [UIImage imageWithCGImage:imageRef scale:0.0 orientation:UIImageOrientationDownMirrored];
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
CGImageRelease(imageRef);
CGImageRelease(imageRef2);
free(rawData);
[_pages replaceObjectAtIndex:_sidebar.selectedIndex withObject:latest];
[_sidebar reloadData];
if(_pages.count > selectedIndex)
{
if([_pages objectAtIndex:selectedIndex])
[_pages replaceObjectAtIndex:selectedIndex withObject:latest];
if([_pagessavedbg objectAtIndex:selectedIndex])
[_pagessavedbg replaceObjectAtIndex:selectedIndex withObject:latest2];
else
[_pagessavedbg insertObject:latest2 atIndex:selectedIndex];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.sidebar reloadData];
[self.sidebar scrollRowAtIndexToVisible:_sidebar.selectedIndex];
});
});
但是,每次调用此代码时(在触摸)时,内存使用情况都会上升约10MB。为什么会发生这种情况?是否有一种更好的,替代的方法来使用多大的内存?
正如贾斯汀注意的,2048 * 1536 * 4 = 12mb。这个事实是数学,无法避免。但是,如果分配12MB是一个问题,则有很多方法可以管理内存利用率(这不是1GB设备上的短期用途内存的实际存储器,因此您应该问您要解决的问题要解决的问题,但是无论如何。...)
- 如果您经常这样做,请不要重新分配内存。重复使用。这样,只需支付一次。
- 如果您不需要2048*1536*4图像,请创建一个较小的位图并扩展图像以适合其。
- 将较小的位图分配给图像的一部分。以后将它们缝在一起。
但是您是否有目标内存分配?尽管视网膜显示一直是许多应用程序的主要内存问题,但短暂的12MB分配通常不是问题。通常是所需的时间,而不是记忆。
如果您必须有2048*1536*4位图,则将需要12MB的内存。