I'm trying to create an image with mask using filter. I have 3 images, all of them with same size:

(lldb) p img1.size
(CGSize) $33 = (width=369, height=370)
(lldb) p img2.size
(CGSize) $34 = (width=369, height=370)
(lldb) p img3.size
(CGSize) $36 = (width=369, height=370)

Then i'm allocating CIImages for them:

CIImage *inputImage = [[CIImage alloc] initWithCGImage:img1.CGImage options:nil];
CIImage *bgImage = [[CIImage alloc] initWithCGImage:img2.CGImage options:nil];
CIImage *maskImage = [[CIImage alloc] initWithCGImage:img3.CGImage options:nil];

And create CIFilter with given CIImages:

CIFilter *filter = [CIFilter filterWithName:@"CIBlendWithMask"];
[filter setValue:inputImage forKey:@"inputImage"];
[filter setValue:bgImage forKey:@"inputBackgroundImage"];
[filter setValue:maskImage forKey:@"inputMaskImage"];
CIImage *outputImage = [filter outputImage];

However, when i'm trying to get outputImage like this:

CGImageRef outputRef = [_context createCGImage:outputImage fromRect:[outputImage extent]];
UIImage *result = [UIImage imageWithCGImage:outputRef];
CGImageRelease(outputRef);

Result image has strange size:

(lldb) p outputImage.size
(CGSize) $37 = (width=738, height=740)

When i take a look into the image, it is located on bottom left (CGContext inverted Y-ax) and has a size of these 3 initial images (width=369, height=370), rest of image size is just empty (alpha = 0.0f). Mask is applied on full area, what is ok.

It may be important, that in the beginning i do something like this:

UIGraphicsBeginImageContextWithOptions(img2.size, NO, 0.0);
UIImage *img1 = UIGraphicsGetImageFromCurrentImageContext(); // transparent image
[anotherImg drawInRect:CGRectMake(0,0,img2.size.width,img2.size.height)];
UIImage *img3 = UIGraphicsGetImageFromCurrentImageContext(); // mask image with proper size
UIGraphicsEndImageContext();

When I use in filter anotherImage instead of img3 as mask, output image is with correct size (img2 is drawn on full area instead of 1/3) however the mask is smaller (1/3 of size while it should be full area). So opposite situation.

What am I doing wrong? How to fix it, so i have both image and mask drawn on full area? As a note - i have to use filter, cant draw with mask in cgcontext.

有帮助吗?

解决方案

You forgot about scaling to retina. This should help:

UIGraphicsBeginImageContextWithOptions(img2.size, NO, img2.scale);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top