I'm working on an app that can change the borders or a rectangular UIImage. The borders will vary, but will look like the UIImage was cut out with scissors, or something to that affect.
What is the best way to do this?
My first thought is to prep a bunch of transparent PNGs with the correct border effect I'm looking for, and then somehow use that as a mask for my UIImage. Is this the right path? Or is there a more flexible programmatic way to do this?
An object that manages image data in your app.
Here are the Core Graphics calls that you can use to mask the image:
//Mask Image
UIImage *inputImage = [UIImage imageNamed:@"inputImage.png"];
CGImageRef maskRef = [UIImage imageNamed:@"mask.png"].CGImage;
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef), NULL, false);
CGImageRef masked = CGImageCreateWithMask([inputImage CGImage], mask);
CGImageRelease(mask);
UIImage *maskedImage = [UIImage imageWithCGImage:masked];
CGImageRelease(masked);
You need image masking for that, I wrote a tutorial on how to use it and how I've used it in my own application.
The following example code should help you get started, it needs the original image and a mask image as input and it returns the masked image as output.
- (UIImage*) maskImage:(UIImage *) image withMask:(UIImage *) mask
{
CGImageRef imageReference = image.CGImage;
CGImageRef maskReference = mask.CGImage;
CGImageRef imageMask = CGImageMaskCreate(CGImageGetWidth(maskReference),
CGImageGetHeight(maskReference),
CGImageGetBitsPerComponent(maskReference),
CGImageGetBitsPerPixel(maskReference),
CGImageGetBytesPerRow(maskReference),
CGImageGetDataProvider(maskReference),
NULL, // Decode is null
YES // Should interpolate
);
CGImageRef maskedReference = CGImageCreateWithMask(imageReference, imageMask);
CGImageRelease(imageMask);
UIImage *maskedImage = [UIImage imageWithCGImage:maskedReference];
CGImageRelease(maskedReference);
return maskedImage;
}
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