0

I've created this method to resize an image.

+ (UIImage *)imageFromImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

All works fine, but if I call this method in another thread it crashes at the drawInRect:

I use these lines to call this method in another thread:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    for (int i = 0; i < [images count]; i++){

        UIImage *img = [UIImage imageWithContentsOfFile:[images objectAtIndex:i]];
        CGFloat wImg = img.size.width * imageViewSize / img.size.height;
        CGSize size = CGSizeMake(wImg, imageViewSize);
        img = [Utility imageFromImage:img scaledToSize:size];

    }
});

How can i do?

Pol
  • 948
  • 1
  • 8
  • 19

2 Answers2

1

As said before, be careful with the UI classes from other threads than the main thread. Try using Core Graphics instead.

Change this line:

[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];

to:

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextConcatCTM(context, CGAffineTransformScale(CGAffineTransformMakeTranslation(0, newSize.height), 1.f, -1.f));
CGContextDrawImage(context, CGRectMake(0, 0, newSize.width, newSize.height), image.CGImage);

The second line will flip your Y-axis, so that it works like the UIKit DrawInRect.

LGP
  • 4,135
  • 1
  • 22
  • 34
0

As a rule of thumb: Always do UI stuff on the main thread.

For detailed information what can be done in background, you have to check documentation carefully:

Not all UIKit classes are thread safe. Be sure to check the documentation before performing drawing-related operations on threads other than your app’s main thread.

From Apples documentation.

According to this answer the behaviour seems to be iOS version specific.

Community
  • 1
  • 1
shallowThought
  • 19,212
  • 9
  • 65
  • 112