2012-10-13 53 views
0

我想不通爲什麼使用GCContext繪製/合併兩個以上的UIImages,使用如此多的內存。我啓用了ARC,並且在使用Instruments查看程序中的內存使用情況時(使用VM跟蹤器工具),我發現以下第一個解決方案僅使用兩個圖像(大約16 MB髒大小和80 MB ResidentSize)的內存,而繪製CGContext使用所有UIImages的內存量(大約468 MB髒大小和520 MB ResidentSize),並最終導致我的應用程序崩潰。 如何確保CGContext的使用量不超過用於兩個UIImage的內存量? 實際上,我喜歡以最小的內存要求和最佳性能完成一種雙緩衝,用於繪製多個相同大小的圖像文件(基於.PNG且已具有透明設置)的圖層。合併兩個以上的圖像會佔用太多的內存,爲什麼?

請注意,我的ViewController包含'UIImageView * imageView'和'CGSize imageSize' 屬性。

下面的代碼被用於只檢查通過加載UIImages消耗的內存量:

- (void)drawUsingTwoUIImages1:(NSMutableArray *)imageFiles 
{ 
    if (! imageFiles.count) { 
     return; 
    } 
    NSString *imageFile1 = [imageFiles objectAtIndex:0]; 
    NSString *filePath1 = [[NSBundle mainBundle] pathForResource:imageFile1 ofType:nil]; 
    UIImage *image1 = [UIImage imageWithContentsOfFile:filePath1]; 
    UIImage *image2 = nil; 
    image1 = [UIImage imageWithContentsOfFile:filePath1]; 
    for (NSInteger index = 1; index < imageFiles.count; index++) { 
     NSString *imageFile2 = [imageFiles objectAtIndex:index]; 
     NSString *filePath2 = [[NSBundle mainBundle] pathForResource:imageFile2 ofType:nil]; 
     image2 = [UIImage imageWithContentsOfFile:filePath2]; 
    } 
} 

下一個代碼I'ld喜歡我最終的應用程序,以顯示所有繪製的圖像文件中使用。我懷疑一些聰明的技巧需要按照CGContext處理的順序來完成,或者可能是CGLayerRef。如果有人能告訴我如何做到這一點,或想出 代碼,我將再次編碼避風港!

- (void)drawUsingTwoUIImages2:(NSMutableArray *)imageFiles 
{ 
    _imageView.image = nil; 
    if (! imageFiles.count) { 
     return; 
    } 
    NSString *imageFile1 = [imageFiles objectAtIndex:0]; 
    NSString *filePath1 = [[NSBundle mainBundle] pathForResource:imageFile1 ofType:nil]; 
    UIImage *image1 = [UIImage imageWithContentsOfFile:filePath1]; 
    UIImage *image2 = nil; 
    for (NSInteger index = 1; index < imageFiles.count; index++) { 
     if (! UIGraphicsGetCurrentContext()) { 
      UIGraphicsBeginImageContext(_imageSize); 
     } 
     NSString *imageFile2 = [imageFiles objectAtIndex:index]; 
     NSString *filePath2 = [[NSBundle mainBundle] pathForResource:imageFile2 ofType:nil]; 
     image2 = [UIImage imageWithContentsOfFile:filePath2]; 
     [image1 drawAtPoint:CGPointMake(0., 0.)]; 
     [image2 drawAtPoint:CGPointMake(0., 0.)]; 
     image1 = UIGraphicsGetImageFromCurrentImageContext(); 
     UIGraphicsEndImageContext(); 
    } 
    _imageView.image = image1; 
} 

上面真的驅使我堅果和沒有任何人看到這裏,我錯過了什麼,或者知道該怎麼做,以獲得最大的性能和最小的內存使用情況?

+0

找出任何好的指針? –

回答

1

我已經知道要走的路是使用CATiledLayer,並且需要在各種比例尺寸下平鋪圖像數據。在Apple的示例代碼中搜索並在StackOverflow中搜索幫助我解決了這個問題。