Question

Here is the issue i am facing:

I have implemented the masking using maskimage.

Here is the Original Image : (Size: 300width x 418height)

enter image description here

Here is the Mask image: (Size: 165width x 215height)

enter image description here

Below is the code i have used to crop image according to mask & create new UIImage:

CALayer *mask = [CALayer layer];
mask.contents = (id)[[UIImage imageNamed:@"maskImage.png"] CGImage];
mask.frame = imgMaskImage.frame;
mask.frame = CGRectMake(mask.frame.origin.x-10, mask.frame.origin.y-50, mask.frame.size.width, mask.frame.size.height);
self.imgEditedImageView.layer.mask = mask;
self.imgEditedImageView.layer.masksToBounds = YES;
imgMaskImage.image = nil;

UIGraphicsBeginImageContext(self.imgEditedImageView.frame.size);
[self.imgEditedImageView.layer renderInContext:UIGraphicsGetCurrentContext()];
croppedImage = UIGraphicsGetImageFromCurrentImageContext();
[croppedImage drawInRect:imgMaskImage.frame];
UIGraphicsEndImageContext();

It works & crops image accordingly. Here is the result:

enter image description here

But the issue the Final croppedImage(UIImage) image takes the frame of original image (300x418).

I am not getting why it happens. I have tried so many things but still no solution. Can any one please suggest me if i am doing anything wrong or something is missing.

Thanks.

Was it helpful?

Solution

- (UIImage *)croppedPhoto {
    // For dealing with Retina displays as well as non-Retina, we need to check
   // the scale factor, if it is available. Note that we use the size of teh cropping Rect
    // passed in, and not the size of the view we are taking a screenshot of.
     CGRect croppingRect = CGRectMake(imgMaskImage.frame.origin.x,
    imgMaskImage.frame.origin.y, imgMaskImage.frame.size.width,
    imgMaskImage.frame.size.height);

    imgMaskImage.hidden=YES;

    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
        UIGraphicsBeginImageContextWithOptions(croppingRect.size, YES,
    [UIScreen mainScreen].scale);
    } else {
        UIGraphicsBeginImageContext(croppingRect.size);
    }

    // Create a graphics context and translate it the view we want to crop so
    // that even in grabbing (0,0), that origin point now represents the actual
    // cropping origin desired:
         CGContextRef ctx = UIGraphicsGetCurrentContext();
         CGContextTranslateCTM(ctx, -croppingRect.origin.x, -croppingRect.origin.y);
    [self.view.layer renderInContext:ctx];

   // Retrieve a UIImage from the current image context:
   UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

    // Return the image in a UIImageView:
   return snapshotImage;

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top