CGContextClearRect with circle

I am creating an app in which i am trying to clear the rect of UIImageView. I have achieved this with CGContextClearRect, but the problem is that it is clearing rect in square shape and i want to achieve this effect in round shape.

What i have tried so far:

  • Reading NFC Tags with iPhone 6 / iOS 8
  • Parsing Html url in iphone
  • App Store submission/distribution error “failed to open ssh session”
  • IOS Run custom shell script 'embed pods framework' file not found error
  • Using enum in Objective-C?
  • Swift: How to remember cookies for further http requests
  • UITouch *touch2 = [touches anyObject];
    CGPoint point = [touch2 locationInView:img];
    
    UIGraphicsBeginImageContextWithOptions(img.bounds.size, NO, 0.0f);
    [img.image drawInRect:CGRectMake(0, 0, img.frame.size.width, img.frame.size.height) blendMode:kCGBlendModeNormal alpha:1.0];
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGRect cirleRect = CGRectMake(point.x, point.y, 40, 40);
    CGContextAddArc(context, 50, 50, 50, 0.0, 2*M_PI, 0);
    CGContextClip(context);
    CGContextClearRect(context,cirleRect);
    //CGContextClearRect(context, CGRectMake(point.x, point.y, 30, 30));
    img.image =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    Solutions Collect From Internet About “CGContextClearRect with circle”

    I’m not sure exactly what you are doing, but your clipping arc isn’t being created correctly. You are creating it at a fixed position which is why it doesn’t really work – except it does, if you click in the top left corner.

    If you want to see it working try this:

    - (IBAction)clearCircle:(UITapGestureRecognizer *)sender {
        UIImageView *imageView = self.imageView;
        UIImage *currentImage = imageView.image;
        CGSize imageViewSize = imageView.bounds.size;
    
        CGFloat rectWidth = 40.0f;
        CGFloat rectHeight = 40.0f;
    
        CGPoint touchPoint = [sender locationInView:imageView];
    
        UIGraphicsBeginImageContextWithOptions(imageViewSize, YES, 0.0f);
        CGContextRef ctx = UIGraphicsGetCurrentContext();
    
        [currentImage drawAtPoint:CGPointZero];
    
        CGRect clippingEllipseRect = CGRectMake(touchPoint.x - rectWidth / 2, touchPoint.y - rectHeight / 2, rectWidth, rectHeight);
        CGContextAddEllipseInRect(ctx, clippingEllipseRect);
    
        CGContextClip(ctx);
    
        CGContextClearRect(ctx, clippingEllipseRect);
    
        imageView.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
    }
    

    Which creates a clipping ellipse (in this case a circle) in the rect 40 x 40 centred at the touch point.

    You can see this in an example project on Bitbucket which you can download for yourself to try