CALayer renderInContext: Crash

你可能會像我一樣,在用renderInContext 這個方法進行截圖的時候,總是出現崩潰現象。確無計可施。我當時研究這個問題也研究了好久,最後通過查找各方的資料,法相,出現這個狀況的原因是這個方法在調用時候系統內存會急劇增加,從而導致內存泄漏,崩潰時候報的錯誤是Message from debugger: Terminated due to memory issue

我當時的代碼是這樣寫的

+ (UIImage *) imageWithView:(UIView *)view{
     
float scale = 1.0f;
   
UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, scale);
   
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
   
UIImage* img = UIGraphicsGetImageFromCurrentImageContext();
   
UIGraphicsEndImageContext();
    view
.layer.contents = nil;
   
return img;
}

看似這樣寫詩文問題的沒大事存在着很大的安全隱患,很容易崩潰。唯一解決辦法只能是把該方法替換掉。通過查閱大量資料,發現了另外一個方法。

 size_t width = _backView.bounds.size.width;

                size_t height = _backView.bounds.size.height;

                

                unsigned char *imageBuffer = (unsigned char *)malloc(width*height*4);

                CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();

                

                CGContextRef imageContext =

                CGBitmapContextCreate(imageBuffer, width, height, 8, width*4, colourSpace,

                                      kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);

                CGColorSpaceRelease(colourSpace);

                [_backView.layer renderInContext:imageContext];

                CGImageRef outputImage = CGBitmapContextCreateImage(imageContext);

                UIImage * myImage =[UIImage imageWithCGImage:outputImage scale:1.0 orientation:z ZZZZZZZ] ;

                     callBack(outputImage,array);

                CGImageRelease(outputImage);

                CGContextRelease(imageContext);

                free(imageBuffer);

換成這個方法就可以解決上述問題了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章