shein
shein

Reputation: 1844

CGContextDrawImage in Retina draws image pixelated?

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);

Upvotes: 11

Views: 6183

Answers (3)

user187676
user187676

Reputation:

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

myLayer.contentsScale = [UIScreen mainScreen].scale

Upvotes: 20

JipZipJib
JipZipJib

Reputation: 81

Updated @Tieme's solution for Swift 4

UIGraphicsBeginImageContextWithOptions(size, false, 0.0)

instead of

UIGraphicsBeginImageContext(size)

Upvotes: 0

Tieme
Tieme

Reputation: 65509

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.

Upvotes: 27

Related Questions