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.
For Swift 4 and plus follow code below
Swift 3 - Simplest Solution I Found
I created an
@IBDesignable
for this so you could see the effect right away on your storyboard.How to use
Example
Notes
The tutorial uses this method with two parameters:
image
andmaskImage
, 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.
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
Then change the name of the variable in 2. to
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?
This works for me.
I tried both code using either CALayer or CGImageCreateWithMask but none of them didn't work for me
But i found out that the problem is with png file format, NOT the code!!
so just to share my finding!
If you want to use
you must use 24bit png without alpha channel
If you want to use CALayer mask, you must use (24bit or 8bit) png with alpha channel where transparent part of your png will mask the image (for smooth gradient alpha mask.. use 24bit png with alpha channel)
SWIFT 3 XCODE 8.1
// for use