0

I have a UIImageView that can be moved/scaled (self.imageForEditing). On top of this image view I have an overlay with a hole cut out, which is static and can't be moved. I need to save just the part of the underlying image that is visible through the hole at the time a button is pressed. My current attempt:

- (IBAction)saveImage
{

    UIImage *image = self.imageForEditing.image;

    CGImageRef originalMask = [UIImage imageNamed:@"picOverlay"].CGImage;
    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(originalMask),
                                        CGImageGetHeight(originalMask),
                                        CGImageGetBitsPerComponent(originalMask),
                                        CGImageGetBitsPerPixel(originalMask),
                                        CGImageGetBytesPerRow(originalMask),
                                        CGImageGetDataProvider(originalMask), nil, YES);

    CGImageRef maskedImageRef = CGImageCreateWithMask(image.CGImage, mask);

    UIImage *maskedImage = [UIImage imageWithCGImage:maskedImageRef scale:image.scale orientation:image.imageOrientation];

    CGImageRelease(mask);
    CGImageRelease(maskedImageRef);

    UIImageView *test = [[UIImageView alloc] initWithImage:maskedImage];
    [self.view addSubview:test];
}

As a test I'm just trying to add the newly created image to the top left of the screen. Theoretically it should be a small round image (the part that was visible through the overlay). But I'm just getting the whole image created again. What am I doing wrong? And how can I account for the fact that self.imageForEditing can be moved around?

jhilgert00
  • 5,479
  • 2
  • 38
  • 54
soleil
  • 12,133
  • 33
  • 112
  • 183

1 Answers1

0

CGImageCreateWithMask returns an image of the same size as the original's one. That is why you get the original image (I assume) with the mask being applied.

You can apply the mask and then remove the invisible border. Use the advice from this question: iOS: How to trim an image to the useful parts (remove transparent border)

Find the bounds of the non-transparent part of the image and redraw it into a new image.

Community
  • 1
  • 1
Anton
  • 726
  • 11
  • 23