Suppose your image is displayed in a view - probably a UIImageView. Then we can punch a rectangular hole in this view by masking the view layer. Each species has a layer. We will apply a mask to this presentation layer, which itself is a layer containing the image that we will generate in the code. The image will be black except for a transparent rectangle somewhere in the middle. This transparent rectangle will cause a hole in the image.
So let self.iv be a UIImageView. Try running this code:
CGRect r = self.iv.bounds; CGRect r2 = CGRectMake(20,20,40,40); // adjust this as desired! UIGraphicsBeginImageContextWithOptions(r.size, NO, 0); CGContextRef c = UIGraphicsGetCurrentContext(); CGContextAddRect(c, r2); CGContextAddRect(c, r); CGContextEOClip(c); CGContextSetFillColorWithColor(c, [UIColor blackColor].CGColor); CGContextFillRect(c, r); UIImage* maskim = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); CALayer* mask = [CALayer layer]; mask.frame = r; mask.contents = (id)maskim.CGImage; self.iv.layer.mask = mask;
For example, in this image, the white square is not a superimposed square, this is the hole showing the white background of the window behind it:

EDIT . I feel obligated since I mentioned this in a comment to show how to do the same with CAShapeLayer. The result is exactly the same:
CGRect r = self.iv.bounds; CGRect r2 = CGRectMake(20,20,40,40); // adjust this as desired! CAShapeLayer* lay = [CAShapeLayer layer]; CGMutablePathRef path = CGPathCreateMutable(); CGPathAddRect(path, nil, r2); CGPathAddRect(path, nil, r); lay.path = path; CGPathRelease(path); lay.fillRule = kCAFillRuleEvenOdd; self.iv.layer.mask = lay;
matt
source share