带圆圈的CGContextClearRect [英] CGContextClearRect with circle
问题描述
我正在创建一个应用程序,我试图清除 UIImageView
的 rect
。我用 CGContextClearRect
实现了这一点,但问题是它正在清除方形中的 rect
并且我想要实现这个效果是圆形的。
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:
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();
推荐答案
我不确定你到底在做什么,但您的剪裁弧未正确创建。你是在一个固定的位置创建它,这就是为什么它不能真正起作用 - 除非你点击左上角。
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();
}
创建剪裁椭圆(在本例中为圆形)在以触摸点为中心的矩形40 x 40中。
Which creates a clipping ellipse (in this case a circle) in the rect 40 x 40 centred at the touch point.
这篇关于带圆圈的CGContextClearRect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!