How can I mask a UIImageView?
I am trying to mask an image with something like this:
Would you please help me?
I am using this code:
- (void) viewDidLoad {
UIImage *OrigImage = [UIImage imageNamed:@"dogs.png"];
UIImage *mask = [UIImage imageNamed:@"mask.png"];
UIImage *maskedImage = [self maskImage:OrigImage withMask:mask];
myUIIMage.image = maskedImage;
}
There's an easier way.
#import <QuartzCore/QuartzCore.h>
// remember to include Framework as well
CALayer *mask = [CALayer layer];
mask.contents = (id)[[UIImage imageNamed:@"mask.png"] CGImage];
mask.frame = CGRectMake(0, 0, <img_width>, <img_height>);
yourImageView.layer.mask = mask;
yourImageView.layer.masksToBounds = YES;
For Swift 4 and plus follow code below
let mask = CALayer()
mask.contents = [ UIImage(named: "right_challenge_bg")?.cgImage] as Any
mask.frame = CGRect(x: 0, y: 0, width: leftBGImage.frame.size.width, height: leftBGImage.frame.size.height)
leftBGImage.layer.mask = mask
leftBGImage.layer.masksToBounds = true
The tutorial uses this method with two parameters: image
and maskImage
, these you have to set when you call the method. An example call could look like this, assuming the method is in the same class and the pictures are in your bundle:
Note - amazingly the images do not even have to be the same size.
...
UIImage *image = [UIImage imageNamed:@"dogs.png"];
UIImage *mask = [UIImage imageNamed:@"mask.png"];
// result of the masking method
UIImage *maskedImage = [self maskImage:image withMask:mask];
...
- (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 maskedImageRef = CGImageCreateWithMask([image CGImage], mask);
UIImage *maskedImage = [UIImage imageWithCGImage:maskedImageRef];
CGImageRelease(mask);
CGImageRelease(maskedImageRef);
// returns new image with mask applied
return maskedImage;
}
After you provided your code I have added some numbers as comments to it for reference. You still have two options. This whole thing is a method, which you are calling somewhere. You don't need to create the images inside it: this reduces the reusability of the method to zero.
To get your code working. Change the methods head (1.) to
- (UIImage *)maskImageMyImages {
Then change the name of the variable in 2. to
UIImage *maskImage = [UIImage imageNamed:@"mask.png"];
The method will return your masked images so you'll have to call this method in some place. Can you show us the code where you are calling your method?