6

I want to mask an image by passing another image as mask. I am able to mask the image but the resulting image doesn't look good. It is jagged at borders.

I guess the problem is related to retina graphics. The scale property for the two images are different as:

  1. The image from which I want to mask has a scale value 1. This image generally has a resolution greater than 1000x1000 pixels.
  2. The image according to which I want the resulting image(image having black and white colors only) has scale value 2. This image is generally of resolution 300x300 pixels.

The resulting image has a scale value of 1.

The code I am using is:

+ (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {

CGImageRef maskRef = maskImage.CGImage;

CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                    CGImageGetHeight(maskRef),
                                    CGImageGetBitsPerComponent(maskRef),
                                    CGImageGetBitsPerPixel(maskRef),
                                    CGImageGetBytesPerRow(maskRef),
                                    CGImageGetDataProvider(maskRef), NULL, false);


CGImageRef masked = CGImageCreateWithMask([image CGImage], mask);
CGImageRelease(mask);
UIImage *maskedImage = [UIImage imageWithCGImage:masked ];
CGImageRelease(masked);
return maskedImage;
}

How can I get a masked image which follows retina scale?

miken32
  • 42,008
  • 16
  • 111
  • 154
Gaurav Singh
  • 1,897
  • 14
  • 22
  • You should consider validate an answer if it helped you. – kokluch May 24 '14 at 13:14
  • I asked this question on July 3rd, 2013 and first answer was on Jan 8. Between that time I have moved to different projects and I haven't checked if the answer helped or not and if I am not sure then how can I accept any answer. I just want to close the question but don't know how to do that. – Gaurav Singh May 24 '14 at 13:22
  • Not that hard to find... – kokluch May 26 '14 at 08:55

2 Answers2

5

I had the same issue. It appears that this line ignore scale factor.

UIImage *maskedImage = [UIImage imageWithCGImage:masked];

So you should draw the image by yourself. Replace it by the following :

UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0);

CGContextRef context = UIGraphicsGetCurrentContext();

CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);

CGContextDrawImage(context, rect, masked);

UIImage * maskedImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

Works fine by me.

EDIT

OR

UIImage * maskedImage = [UIImage imageWithCGImage:masked 
                                            scale:[[UIScreen mainScreen] scale] 
                                      orientation:UIImageOrientationUp];
kokluch
  • 602
  • 5
  • 16
5

You can do

UIImage * maskedImage = [UIImage imageWithCGImage:masked scale:[[UIScreen mainScreen] scale] orientation:UIImageOrientationUp];
user3256777
  • 61
  • 1
  • 2