CGContextClearRect with circle

I am creating an application in which I am trying to clear rect

from UIImageView

. I achieved this with help CGContextClearRect

, but the problem is that it clears rect

in a square shape and I want to achieve this effect in a round shape.

What I've tried so far:

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();

      

+3


source to share


1 answer


I'm not sure what you are doing, but your clipping arc is not being generated correctly. You create it at a fixed position, so it doesn't really work - other than that if you click on the top left.

If you want to see it 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();

}

      



Creates a trimming ellipse (in this case, a circle) within a 40 x 40 rectangle centered on the tangent point.

You can see this in the Bitbucket sample project you can download for yourself to try

+2


source







All Articles