Memory release timing when drawingInRect is turned to for statement in UIImage resize

Asked 2 years ago, Updated 2 years ago, 33 views

Created a method to resize UIImage.When I write the process of taking out the elements of the image array and resizing them one by one, the memory does not open well, and if high-definition images are resized many times, the memory will run out.If I want to write the following code in an ARC environment, how should I free up memory?

"It seems that ""trimmedImage"" has not been opened, so please let me know if there is any way to forcefully open the trimmedImage."(*I tried using @autoreleasepool and trimmedImage=nil; but it didn't open until the next loop, so I only used more memory.)

 + (void) cropImages: (NSArray*) images {
    for(__weak UIImage* image in images) {
        UIImage*reservedImage=[selfcropRectImage:image];
    }
}


+ (UIImage*) cropRectImage: (UIImage*) image{
    float = image.size.width;
    float = image.size.height;
    CGRect;

    if(h<=w){
        float x = w/2 - h/2;
        floaty = 0;
        rect = CGRectMake(x,y,h,h);
    } else {
        float x = 0;
        floaty = h/2 - w/2;
        rect = CGRectMake(x,y,w,w);
    }

    CGIMAGERef cgImage=CGIMAGECreateWithImageInRect(image.CGIMAGE, rect);
    UIImage* trimmedImage= [UIImage imageWithCGImage:cgImage];

    CGSize newSize = CGSizeMake (320,320);
    UIGraphicsBeginImageContext (newSize);
    UIImage*reservedImage=nil;
    trimmedImage drawInRect: CGRectMake(0,0, newSize.width, newSize.height);
    // TODO: It should be AutoReleased here... (http://vladimir.zardina.org/2010/05/resizing-uiimage-objects/)
    resizedImage=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    image=nil;
    cgImage=nil;

    return resizedImage;
}

ios objective-c xcode

2022-09-29 21:47

1 Answers

The reason is CGImageRef release failure as already resolved in the comment.

In this case, I draw with two hands, trimming and resizing, but the image size for trimming is large, plus CGImageRef, so I have to explicitly release it. If you set origin in the negative direction during resizing, it will be easy.

 + (UIImage*) cropRectImage: (UIImage*) image{
    CGFlow=image.size.width, h=image.size.height;
    float scale=(h<w)?320/h:320/w;
    CGSize size = CGSizeMake (w*scale, h*scale);

    UIGraphicsBeginImageContext (CGSizeMake (320,320));
    image drawInRect: CGRectMake(320-size.width)/2, (320-size.height)/2, size.width, size.height);
    UIImage*reservedImage=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return resizedImage;
}


2022-09-29 21:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.