William Falcon
William Falcon

Reputation: 9813

Make part of UIImage transparent, or crop that region

I have a UIImage like so: enter image description here

I want to remove a rect in the middle to leave it like so: enter image description here

Upvotes: 0

Views: 1100

Answers (3)

Paul.s
Paul.s

Reputation: 38728

The easiest way to punch a hole through would be to add a layer mask.

  • #import <QuartzCore/QuartzCore.h>
  • Create the path you want to clip (the rect you want to punch through)

    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRect:yourView.bounds];
    [maskPath appendPath:[UIBezierPath bezierPathWithRect:rectToPunchThroughTheView]];
    
  • Then create a mask layer and add it to your view - CAShapeLayer will allow you to define any path

    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.fillRule  = kCAFillRuleEvenOdd;
    maskLayer.fillColor = [UIColor blackColor].CGColor;
    maskLayer.path      = maskPath.CGPath;
    
    yourView.layer.mask = maskLayer;
    

Upvotes: 10

Anand Suthar
Anand Suthar

Reputation: 3798

You can do this way

        CGRect fullimageRect;
        CGRect upperRect;
        CGRect lowerRect;

        UIImage *upperImage;
        UIImage *lowerImage;
        UIImage *finalImage;

        UIGraphicsBeginImageContext(upperRect.size);
        [[UIImage imageNamed:@"yourimage.png"] drawInRect:lowerRect];
        upperImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();


        UIGraphicsBeginImageContext(lowerRect.size);
        [[UIImage imageNamed:@"yourimage.png"] drawInRect:lowerRect];
        lowerImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        NSLog(@"%@",upperImage);
        NSLog(@"%@",lowerImage);


        UIGraphicsBeginImageContext(fullimageRect.size);
        [upperImage drawInRect:upperRect];
        [lowerImage drawInRect:lowerRect];
        finalImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        NSLog(@"%@",finalImage);

Upvotes: 1

Groot
Groot

Reputation: 14251

I would create a UIImage category and crop the image two times with different rects.

Here is the method I added yo my UIImage category a while ago that suited my needs good:

- (UIImage *)cropWithRect:(CGRect)rect {

    // If run on a retina device scale is 2 else 1
    rect = CGRectMake(rect.origin.x * self.scale,
                      rect.origin.y * self.scale,
                      rect.size.width * self.scale,
                      rect.size.height * self.scale);

    CGImageRef imgRf = CGImageCreateWithImageInRect(self.CGImage, rect);
    UIImage *croppedImage = [UIImage imageWithCGImage:imageRef 
                                                scale:self.scale
                                          orientation:self.imageOrientation];
    CGImageRelease(imageRef);

    return croppedImage;

}

Upvotes: 2

Related Questions