I want to mask two images
Image 1:
Image 2:
Now i want to merge this two images like The image2 will come in centre of the image1.
I've read Any idea why this image masking code does not work? and "How to Mask an Image"
But on using this function:-
- (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);
return [UIImage imageWithCGImage:masked];
}
But by using this function I got the output is :-
As far as I can tell the problem is not with maskImage:withMask:
. The wrong output you posted is not wrong: where the pixels of image1 are black, image2 is not visible.
The problem is probably or in the functions you used to load image
and mask
, or in the code producing the graphical output.
Actually it seems to me that you got the right output, but using the wrong colorspace (grayscale without alpha). Check if the argument image
you supply is actually in RGBa format, and if the returned UIImage
isn't drawn onto some other CGContext
using DeviceGray as colorspace.
The other possible cause that comes to my mind is that you inverted image1 and image2. According to the documentation, mask
should be scaled up to the size of image
(see below) but you have a small image there. This seems reasonable also because image1 is in grayscale, although when I tried to swap image1 and image2 I got image1 unmodified as output.
To run the tests I used the images attached, and then copied & pasted the method -(UIImage *)maskImage:(UIImage *)image withMask:(UIImage *)maskImage
as it is.
I used a simple iOS project with one view and an UIImageView
inside (with tag 1), and the following code in the controller:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIImageView *imageView=(UIImageView *)[self.view viewWithTag:1];
UIImage *im1=[UIImage imageNamed:@"image1"];
UIImage *im2=[UIImage imageNamed:@"image2"];
imageView.image=[self maskImage:im2 withMask:im1];
}
I get the following output (which is right):
If by mistake you invert im1 with im2, you get instead image1 unmodified.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With