11

I need to draw images into a CALayer because I need to perform various effects, animations and filters on it. When I do simple drawing into the CGContext no matter what I do it always gets drawn pixelated... What's the right way to draw onto a context in retina?

This is what I'm doing now:

CGImageRef plateImage = [[UIImage imageNamed:@"someImage"] CGImage];
CGFloat width = CGImageGetWidth(plateImage), height = CGImageGetHeight(plateImage);
CGFloat scale = [[UIScreen mainScreen] scale];

NSLog(@"Scale: %f\nWidth: %f\nHeight: %f", scale, width, height);
CGContextTranslateCTM(_context, 0, height / scale);
CGContextScaleCTM(_context, 1.0, -1.0);

CGContextDrawImage(_context, CGRectMake(0, 0, width / scale, height / scale), plateImage);
shein
  • 1,834
  • 15
  • 23

3 Answers3

27

I had the same problem but the solution didn't seem to work.

UIGraphicsBeginImageContext() turned out to be causing my problem. I'm posting my solution here for future users with the same problem.

From iOS 4.0 you should use:

UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);

instead of

UIGraphicsBeginImageContext(size);

If you don't want pixelated images.

Tieme
  • 62,602
  • 20
  • 102
  • 156
  • Thank you! I can't say I understand why this works, but it does. – anonymouse Jul 05 '13 at 22:23
  • 2
    Worth noting that I had the best results combining this with the accepted answer: `UIGraphicsBeginImageContextWithOptions(imageSize, NO, [UIScreen mainScreen].scale);` – bplattenburg Oct 02 '15 at 18:21
20

You need to set the contents scale of the layer appropriately.

myLayer.contentsScale = [UIScreen mainScreen].scale
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
  • Aaaaaa! I was looking everywhere in CG docs - didn't think for a minute it was a layer issue! Thank you! – shein Feb 25 '12 at 17:02
0

Updated @Tieme's solution for Swift 4

UIGraphicsBeginImageContextWithOptions(size, false, 0.0)

instead of

UIGraphicsBeginImageContext(size)
JipZipJib
  • 81
  • 3
  • 5