UIImage's drawInrect: smoothes image

2019-02-11 19:37发布

问题:

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

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

Any ideas?

Thanks in advance.

回答1:

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