IOS: retinal scaling masking

I want to mask an image by passing another image as a mask. I can mask the image, but the resulting image does not look very good. It is serrated within the boundaries.

I think the problem is with the graphics of the retina. The scale property for the two images is different:

  • The image I want to mask from has a scale value of 1. This image usually has a resolution of more than 1000x1000 pixels.
  • The image, according to which I want to get the resulting image (only with black and white colors), has a scale value of 2. This image, as a rule, has a resolution of 300 × 300 pixels.

The resulting image has a scale value of 1.

The code I use 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 that follows the retinal scale?

+6
source share
2 answers

I had the same problem. This line seems to ignore the scale factor.

 UIImage *maskedImage = [UIImage imageWithCGImage:masked]; 

So you have to draw the image yourself. Replace it as follows:

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

It works great.

EDIT

OR

 UIImage * maskedImage = [UIImage imageWithCGImage:masked scale:[[UIScreen mainScreen] scale] orientation:UIImageOrientationUp]; 
+5
source

You can do

 UIImage * maskedImage = [UIImage imageWithCGImage:masked scale:[[UIScreen mainScreen] scale] orientation:UIImageOrientationUp]; 
+4
source

Source: https://habr.com/ru/post/948624/


All Articles