16

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.

tonytony
  • 1,994
  • 3
  • 20
  • 27

1 Answers1

30

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);
}
sergio
  • 68,819
  • 11
  • 102
  • 123
  • 2
    I wouldn't recommend checking float equality using `==`. All you have to do is set the scale to `0.f`, and the framework will take care of the rest. (see http://stackoverflow.com/questions/2765537/how-do-i-use-the-nsstring-draw-functionality-to-create-a-uiimage-from-text) – Mazyod Sep 14 '12 at 16:40
  • 1
    Thank you very much! This solves the issue. `if ([UIScreen instancesRespondToSelector:@selector(scale)])` -- is this line for iOS3 support? `scale` property is supported starting from iOS 4.0. – tonytony Sep 14 '12 at 18:13
  • @Mazyod Am I correct in understanding that `0.0f` will make the framework handle the correct scale, regardless of whether that is retina or non-retina on the currect device? – Timo Jan 03 '13 at 11:55
  • @Timo Yep! Again, check the post I linked for more info. – Mazyod Jan 03 '13 at 17:33
  • 3
    I would recommend using `[UIScreen mainScreen].scale` instead of hardcoded `@2x` because iPhone 6+'s scale is 3x. – nemesis Dec 30 '14 at 15:36