I’m fetching an image and saving it to temporary directory in a background thread. Before saving, I want to add a little white border to this UIImage. I’m doing this:
- (UIImage *)imageWithBorder:(UIImage *)image {
CGSize newSize = CGSizeMake(image.size.width, image.size.height);
CGRect rect = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
UIGraphicsBeginImageContextWithOptions(newSize, NO, image.scale); {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextBeginTransparencyLayer (context, NULL);
//Draw
[image drawInRect:rect blendMode:kCGBlendModeNormal alpha:1.0];
CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
CGContextStrokeRectWithWidth(context, rect, 10);
CGContextEndTransparencyLayer(context);
}
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result;
}
Everything is okay, after loading that image from a temporary directory I can see border on an image, but in console I’m getting invalid context 0x0 when the code below implements. What’s wrong here?
Update 01
- (UIImage *)imageWithBorder:(UIImage *)image {
CGSize newSize = CGSizeMake(image.size.width, image.size.height);
CGRect rect = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
UIGraphicsBeginImageContextWithOptions(newSize, NO, image.scale); {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawImage (context, rect, [image CGImage]);
CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
CGContextStrokeRectWithWidth(context, rect, 10);
}
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result;
}
Try changing:
to
Also, why use a transparency layer? You have the alpha set to 1, so you could just overwrite the original image, no?
EDIT: I just ran the same code in my app, on the background, it worked flawlessly:
When I do this in viewDidAppear: (but its a small image, maybe the size is relevant?)
this is all I see in the log:
So something else is going on with you code. I’m building with Xcode 4.4.1, deployment target is 5.1
EDIT: In your block, you cannot refer to “cell” as cell is temporal – with recycling it may not even be visible. So the image name will be routed through a local NSString, then at the end, you need another method that the image can be posted to, along with the cell indexPath. That method will see if that indexPath is in the visibleCells of the table, if so then update the image, if not you want to store the image so it can be used with the tableView next asks for the cell.
EDIT2: This code:
Should be turned into something that does not involve “cell” as cell may go out of scope or be used by another index (assuming recycling). Something like this:
Your method determines if that cell is visible, if so update the image, if not save it so next time you need it you have it.