Syed Sharjeel Ali
Syed Sharjeel Ali

Reputation: 134

How to get UIBezierPath of shape in UIImage or crop UIImage in a certain shape

I am new in iOS, I want to know if I can get the UIBezierPath of a UIImage. I have a UIImage of face layout and want to get the UIBezierPath, which helps me in cropping the UIImage. Or, can any one tell me about other ways of cropping UIImages?, but make sure cropping is in a custom shape (like: face, heart etc), not in a rectangle.

Upvotes: 4

Views: 1302

Answers (1)

Keenle
Keenle

Reputation: 12190

Here is the code to mask image with image:

- (UIImage *)cerateImageFromImage:(UIImage *)image
                    withMaskImage:(UIImage *)mask {
    CGImageRef imageRef = image.CGImage;
    CGImageRef maskRef = mask.CGImage;

    CGImageRef imageMask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                             CGImageGetHeight(maskRef),
                                             CGImageGetBitsPerComponent(maskRef),
                                             CGImageGetBitsPerPixel(maskRef),
                                             CGImageGetBytesPerRow(maskRef),
                                             CGImageGetDataProvider(maskRef),
                                             NULL,
                                             YES);

    CGImageRef maskedReference = CGImageCreateWithMask(imageRef, imageMask);
    CGImageRelease(imageMask);

    UIImage *maskedImage = [UIImage imageWithCGImage:maskedReference];
    CGImageRelease(maskedReference);

    return maskedImage;
}

Usage:

UIImage *image = [UIImage imageNamed:@"Photo.png"];
UIImage *mask = [UIImage imageNamed:@"Mask.png"];
self.imageView.image = [self cerateImageFromImage:image
                                     withMaskImage:mask];

Upvotes: 4

Related Questions