Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImage's drawInrect: smoothes image

I'm trying to draw image using UIImage's drawInRect: method. Here is the code:

UIImage *image = [UIImage imageNamed:@"OrangeBadge.png"];

UIGraphicsBeginImageContext(image.size);

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

UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

The problem is that the resulting image is blurry. Here is the resulting image (on the right side) compared to the source image (on the left side):

Source image and blurred image

I've tried both CGContextSetAllowsAntialiasing(UIGraphicsGetCurrentContext(), NO) CGContextSetShouldAntialias(UIGraphicsGetCurrentContext(), NO) but this did not solve the problem.

Any ideas?

Thanks in advance.

like image 686
tonytony Avatar asked Sep 14 '12 15:09

tonytony


1 Answers

If you are developing on a retina device, possibly the issue is related to the resolution of your graphics context. Would you try with:

UIGraphicsBeginImageContextWithOptions(size, NO, 2.0f);

This will enable retina resolution. Also, your image should be available at @2x resolution for this to work.

If you want to support non-retina devices as well, you can use:

if ([UIScreen instancesRespondToSelector:@selector(scale)]) {
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0f);
} else {
    UIGraphicsBeginImageContext(newSize);
}
like image 173
sergio Avatar answered Nov 02 '22 10:11

sergio